'use client'

import { useState, useEffect, useRef, useCallback, useMemo } from "react"
import { useRouter, useSearchParams } from "next/navigation"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Progress } from "@/components/ui/progress"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import {
  IconActivity,
  IconUsers,
  IconBed,
  IconAlertTriangle,
  IconTrendingUp,
  IconEye,
  IconChartBar,
  IconTarget,
  IconFolder,
  IconMap,
  IconDatabase,
  IconCalendar,
  IconPhoto
} from "@tabler/icons-react"
import {
  HeatmapChart,
  TrendChart,
  UtilizationChart
} from "@/components/modern-charts"
import { useI18n, LanguageSwitcher } from "@jjk/guo"
import { UserRole, RoleDisplayNames, PermissionChecker } from "@jjk/Permissions"
import { AuthManager } from "@/lib/users"
import { UserDropdown } from "@/components/user-dropdown"
import VisualizationDashboard from "@/components/dashboard/VisualizationDashboard"
import DataManagementPanel from "@/components/DataManagementPanel"
import { HospitalMapViewer as OldHospitalMapViewer, HospitalMapViewerRef, POIData, StoreData } from '@/components/HospitalMapViewer'
import AIAssistant from '@/components/AIAssistant'
import { hospitalDB } from '@/lib/indexedDB'
import { config, AMAP_KEY, DEFAULT_CENTER, DEFAULT_ZOOM } from '@/lib/config'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { toast } from 'sonner'
import * as THREE from 'three'
import { realDataService } from '@/lib/realData'
import { api } from '@/lib/api'
import { EmergencyEvent, emergencyService } from '@/lib/emergencyEvents'
import EmergencyPanel from '@/components/EmergencyPanel'
import OcrDashboard from '@/components/OcrDashboard'
import AdvancedUserManagement from '@/components/AdvancedUserManagement'
import OllamaLlavaAssistant from '@/components/OllamaLlavaAssistant'
import { poiCatalog } from '@/lib/poiCatalog'
import AppointmentManagement from '../appointment-management/page'
import BannerManagement from '../banner-management/page'

// 定义数据类型
interface Department {
  id: string
  name: string
  floor: string
  capacity: number
  director?: string
  phone?: string
  currentPatients?: number
  waitingTime?: number
  utilizationRate?: number
}

interface Equipment {
  id: string
  name: string
  type: string
  location: string
  status: string
  uptime: string
  maintenance: string
  currentUtilization?: number
}

interface Alert {
  id: string
  type: string
  severity: string
  title: string
  location: string
  description: string
  timestamp: string
  status: string
  assignee: string
}

export default function MedicalDashboard() {
  const { t, locale } = useI18n()
  const router = useRouter()
  const [selectedMenu, setSelectedMenu] = useState('dashboard')
  const [selectedTab, setSelectedTab] = useState('dashboard')
  
  // 地图管理相关状态
  // const viewerRef = useRef<{ flyTo: (lngLat: [number, number], zoom: number) => void; addPOI: (poi: POIData) => void; addStore: (store: StoreData) => void } | null>(null)
  const [selectedPosition, setSelectedPosition] = useState<[number, number] | null>(null)
  const [, setRealTimeData] = useState<ReturnType<typeof realDataService.getAllRealTimeData> | null>(null)
  const [selectedModel, setSelectedModel] = useState<{ object: THREE.Object3D, point: THREE.Vector3 } | null>(null)
  const [showAddPOI, setShowAddPOI] = useState(false)
  const [showAddStore, setShowAddStore] = useState(false)
  const [pois, setPOIs] = useState<POIData[]>([])
  const [stores, setStores] = useState<StoreData[]>([])
  const [emergencies, setEmergencies] = useState<EmergencyEvent[]>([])
  const [, setSelectedEmergency] = useState<EmergencyEvent | null>(null)

  // 患者统计数据状态
  const [patientStats, setPatientStats] = useState({
    todayAppointments: { count: 0, change: 0 },
    inPatients: { count: 0, change: 0 },
    todayBookings: { count: 0, change: 0 },
    emergencyPatients: { count: 0, change: 0 }
  })
  const [todayPatients, setTodayPatients] = useState<Array<{
    id: string;
    name: string;
    age: number;
    department: string;
    time: string;
    status: string;
  }>>([])
  const [inpatientOverview, setInpatientOverview] = useState<Array<{
    department: string;
    patients: number;
    beds: number;
    utilizationRate: number;
  }>>([])
  const [patientStatsLoading, setPatientStatsLoading] = useState(false)

  // 站点管理相关状态
  interface HospitalSite {
    id: string
    name: string
    center: [number, number]
    zoom: number
    address?: string
    district?: string
    city?: string
    province?: string
  }

  const [sites, setSites] = useState<HospitalSite[]>([
    {
      id: 'default',
      name: '默认医院',
      center: DEFAULT_CENTER,
      zoom: DEFAULT_ZOOM,
      address: '浙江省杭州市'
    }
  ])
  const [currentSiteId, setCurrentSiteId] = useState<string>('default')
  const [currentSite, setCurrentSite] = useState<HospitalSite | null>(null)
  const mapViewerRef = useRef<HospitalMapViewerRef>(null)
  const searchParams = useSearchParams()
  
  // POI表单状态
  const [poiForm, setPOIForm] = useState({
    name: '',
    type: 'department' as POIData['type'],
    floor: 'L1',
    description: ''
  })

  // 商铺表单状态
  const [storeForm, setStoreForm] = useState({
    name: '',
    business: '',
    description: ''
  })
  
  // const [kpiData, setKpiData] = useState({
  //   bedUsage: 89.5,
  //   deviceRate: 96.2,
  //   satisfaction: 94.8
  // })
  // const [flowData, setFlowData] = useState([
  //   { dept: "急诊科", flow: 85 },
  //   { dept: "心内科", flow: 62 },
  //   { dept: "外科", flow: 78 },
  //   { dept: "儿科", flow: 45 }
  // ])
  const [isFullscreen, setIsFullscreen] = useState(false)
  const [screenSize, setScreenSize] = useState<'sm' | 'md' | 'lg' | 'xl' | '2xl'>('lg')
  const [isSidebarCollapsed, setIsSidebarCollapsed] = useState(false)
  const [windowSize, setWindowSize] = useState({ width: 0, height: 0 })
  const [isMobile, setIsMobile] = useState(false)
  const [isTablet, setIsTablet] = useState(false)
  const [scaleFactor, setScaleFactor] = useState(1)
  const [baseFontSize, setBaseFontSize] = useState(16)
  
  // 处理 URL 深链的 poiIds= id1,id2,... 并直接渲染与定位
  const deepLinkPoiIds = useMemo(() => {
    const raw = searchParams?.get('poiIds') || ''
    return raw.split(',').map(s => s.trim()).filter(Boolean)
  }, [searchParams])

  // URL 深链 POI 渲染与定位
  useEffect(() => {
    if (!mapViewerRef.current) return
    if (deepLinkPoiIds.length === 0) return

    console.log('处理深链 POI:', deepLinkPoiIds)

    // 初始化演示 POI（如果还未初始化）
    if (poiCatalog.getAllPOIs().length === 0) {
      console.log('初始化Demo POI...')
      poiCatalog.initDemoPOIs()
    }

    const poisToRender = poiCatalog.getByIds(deepLinkPoiIds)
    if (poisToRender.length === 0) {
      console.warn('未找到指定的 POI:', deepLinkPoiIds)
      return
    }

    console.log('找到 POI:', poisToRender)

    // 渲染 POI
    poisToRender.forEach(poi => {
      mapViewerRef.current?.addPOI?.(poi)
    })

    // 定位到第一个 POI
    const target = poisToRender[0]
    const targetZoom = Number(searchParams?.get('zoom')) || 18
    
    const success = mapViewerRef.current?.flyTo?.(target.position, targetZoom)
    if (!success) {
      // 如果地图还未准备好，延迟重试
      setTimeout(() => {
        mapViewerRef.current?.flyTo?.(target.position, targetZoom)
      }, 800)
    }

    toast.success(`已定位到 ${target.name}`, {
      description: `共显示 ${poisToRender.length} 个POI点位`
    })
  }, [deepLinkPoiIds, searchParams])
  
  // 地图点击回调函数
  const handleMapClick = useCallback((lngLat: [number, number]) => {
    console.log('🎯 Dashboard 收到地图点击:', lngLat)
    console.log('🔄 更新 selectedPosition 状态...')
    setSelectedPosition(lngLat)
    setSelectedModel(null)
    console.log('✅ 状态更新完成')
    toast.success(`地图坐标: ${lngLat[0].toFixed(6)}, ${lngLat[1].toFixed(6)}`)
  }, [])
  
  // 在控制台显示 handleMapClick 函数信息，用于调试
  console.log('🔍 Dashboard handleMapClick 函数:', handleMapClick?.toString().substring(0, 100))
  
  // 右侧卡片动画状态
  // const [perfValues, setPerfValues] = useState<number[]>([0, 0, 0, 0])
  // const [deviceValues, setDeviceValues] = useState<number[]>([0, 0, 0, 0])

  // useEffect(() => {
  //   // 轻微延迟触发入场动画
  //   const t = setTimeout(() => {
  //     // 使用双 RAF 确保浏览器完成首次绘制，再应用过渡
  //     requestAnimationFrame(() => {
  //       requestAnimationFrame(() => {
  //         setPerfValues([75, 68, 82, 45])
  //         setDeviceValues([98.5, 95.2, 99.1, 99.8])
  //       })
  //     })
  //   }, 60)
  //   return () => clearTimeout(t)
  // }, [])

  // 从认证管理器获取当前用户信息
  const [currentUser, setCurrentUser] = useState<ReturnType<typeof AuthManager.getCurrentUser>>(null) // 初始化为null避免hydration错误
  const [isMounted, setIsMounted] = useState(false)
  // 获取并规范化用户角色
  const getCurrentUserRole = (): UserRole => {
    if (!currentUser?.role) return UserRole.DOCTOR
    
    const role = currentUser.role
    if (typeof role === 'string') {
      const roleMapping: { [k: string]: UserRole } = {
        'admin': UserRole.SUPER_ADMIN,
        'super_admin': UserRole.SUPER_ADMIN,
        'dean': UserRole.DEAN,
        'director': UserRole.DIRECTOR,
        'doctor': UserRole.DOCTOR,
        'nurse': UserRole.NURSE,
        'user': UserRole.DOCTOR,
        'manager': UserRole.DEAN,
        'guide': UserRole.NURSE,
        'security': UserRole.DOCTOR
      }
      return roleMapping[role] || UserRole.DOCTOR
    }
    return role as UserRole
  }
  
  const currentUserRole = getCurrentUserRole()

  // 检查登录状态 - 简化版本，因为AuthGuard已经处理了认证
  useEffect(() => {
    setIsMounted(true)
    
    // 只获取用户信息，不做重复的认证检查
    const user = AuthManager.getCurrentUser()
    if (user) {
      console.log('[Dashboard] 用户信息:', {
        username: user.username,
        role: user.role,
        roleType: typeof user.role
      })
      setCurrentUser(user)
    }
  }, [])

  // 加载患者统计数据
  const loadPatientStats = useCallback(async () => {
    if (patientStatsLoading) return
    
    try {
      setPatientStatsLoading(true)
      
      // 并行请求所有患者统计数据
      const [overviewRes, outpatientsRes, inpatientRes] = await Promise.all([
        api.patientStats.getOverview(),
        api.patientStats.getTodayOutpatients(),
        api.patientStats.getInpatientOverview()
      ])
      
      if (overviewRes.success) {
        setPatientStats(overviewRes.data)
      }
      
      if (outpatientsRes.success) {
        setTodayPatients(outpatientsRes.data)
      }
      
      if (inpatientRes.success) {
        setInpatientOverview(inpatientRes.data)
      }
      
    } catch (error) {
      console.error('加载患者统计数据失败:', error)
      toast.error('加载患者数据失败，请刷新重试')
    } finally {
      setPatientStatsLoading(false)
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []) // 故意移除patientStatsLoading依赖，避免无限循环

  // 当选择患者管理菜单时加载数据
  useEffect(() => {
    if (selectedMenu === 'patients' && isMounted) {
      loadPatientStats()
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps  
  }, [selectedMenu, isMounted]) // 故意移除loadPatientStats依赖，避免无限循环

  // 防抖函数
  const debounce = useCallback(<T extends unknown[]>(func: (...args: T) => void, delay: number) => {
    let timeoutId: NodeJS.Timeout
    return (...args: T) => {
      clearTimeout(timeoutId)
      timeoutId = setTimeout(() => func(...args), delay)
    }
  }, [])

  // 响应式检测和窗口大小监听
  useEffect(() => {
    const updateScreenSize = () => {
      const width = window.innerWidth
      const height = window.innerHeight
      setWindowSize({ width, height })
      
      // 检测设备类型
      const userAgent = navigator.userAgent.toLowerCase()
      const isMobileDevice = /mobile|android|iphone|ipad|phone|blackberry|opera|mini|windows\sce|palm|smartphone|iemobile/.test(userAgent)
      const isTabletDevice = /ipad|android(?!.*mobile)|tablet|kindle|silk|playbook|rim\stablet/.test(userAgent)
      
      setIsMobile(isMobileDevice && width < 768)
      setIsTablet(isTabletDevice || (width >= 768 && width < 1024))
      
      // 计算动态缩放因子 (基于1920px宽度)
      const baseWidth = 1920
      const scale = Math.max(0.6, Math.min(1.5, width / baseWidth))
      setScaleFactor(scale)
      
      // 计算基础字体大小
      const fontSize = Math.max(12, Math.min(20, 16 * scale))
      setBaseFontSize(fontSize)
      
      if (width < 640) {
        setScreenSize('sm')
        setIsSidebarCollapsed(true)
      } else if (width < 768) {
        setScreenSize('md')
        setIsSidebarCollapsed(true)
      } else if (width < 1024) {
        setScreenSize('lg')
        setIsSidebarCollapsed(false)
      } else if (width < 1280) {
        setScreenSize('xl')
        setIsSidebarCollapsed(false)
      } else {
        setScreenSize('2xl')
        setIsSidebarCollapsed(false)
      }
    }

    // 初始化
    updateScreenSize()
    
    // 创建防抖版本的updateScreenSize
    const debouncedUpdateScreenSize = debounce(updateScreenSize, 100)
    
    // 添加resize监听
    window.addEventListener('resize', debouncedUpdateScreenSize)
    
    return () => {
      window.removeEventListener('resize', debouncedUpdateScreenSize)
    }
  }, [debounce])

  // 站点管理逻辑
  const handleSiteSelect = useCallback((siteId: string) => {
    const isCurrentSite = currentSiteId === siteId
    setCurrentSiteId(siteId)
    const site = sites.find(s => s.id === siteId)
    
    if (site) {
      setCurrentSite(site)
      localStorage.setItem('current_site_id', siteId)
      
      if (!isCurrentSite) {
        // 只有在真正切换站点时才清除状态，避免重复点击同一站点清除定位高亮
        setSelectedPosition(null)
        
        // 清除地图中的选中状态和高亮效果
        if (mapViewerRef.current) {
          mapViewerRef.current.clearSelectedPOI()
          mapViewerRef.current.clearHighlight()
        }
        
        toast.success(`已切换到: ${site.name}`)
        console.log('站点切换:', { from: currentSiteId, to: siteId, site })
      } else {
        console.log('重新选择当前站点:', { siteId, site })
        // 重新选择当前站点，创建定位高亮效果
        if (mapViewerRef.current) {
          setTimeout(() => {
            mapViewerRef.current?.flyTo(site.center, site.zoom)
          }, 100)
        }
        toast.info(`重新定位到: ${site.name}`)
      }
    }
  }, [sites, currentSiteId])

  // const handleSitesChange = useCallback((newSites: HospitalSite[]) => {
  //   setSites(newSites)
  //   localStorage.setItem('hospital_sites', JSON.stringify(newSites))
  // }, [])

  // 更新当前选中的医院
  useEffect(() => {
    const site = sites.find(s => s.id === currentSiteId)
    setCurrentSite(site || sites[0] || null)
  }, [sites, currentSiteId])

  // 处理突发事件相关函数
  const handleEmergencySelect = useCallback((emergency: EmergencyEvent) => {
    setSelectedEmergency(emergency)
    
    // 在地图上定位到突发事件位置
    if (mapViewerRef.current) {
      mapViewerRef.current.highlightEmergency(emergency.id)
    }
  }, [])
  
  const handleEmergencyCreate = useCallback((emergency: EmergencyEvent) => {
    setEmergencies(prev => [...prev, emergency])
    
    // 将突发事件添加到地图上
    if (mapViewerRef.current) {
      mapViewerRef.current.addEmergency(emergency)
    }
  }, [])
  
  // 初始化突发事件系统
  useEffect(() => {
    // 加载已有的突发事件
    const activeEvents = emergencyService.getActiveEmergencies()
    setEmergencies(activeEvents)
    
    // 添加监听器
    const unsubscribe = emergencyService.addListener((events) => {
      setEmergencies(events)
    })
    
    return () => {
      unsubscribe()
    }
  }, [])
  
  // 生成更自然的POI分布坐标
  const generateNaturalPOILayout = (count: number, baseCenter: [number, number], area: 'left' | 'right' = 'left') => {
    const positions: [number, number][] = []
    const radius = 0.004 // 分布半径
    const minDistance = 0.0008 // 最小间距
    
    for (let i = 0; i < count; i++) {
      let attempts = 0
      let position: [number, number]
      
      do {
        // 生成随机位置
        const angle = (i / count) * 2 * Math.PI + (Math.random() - 0.5) * 0.5
        const distance = Math.random() * radius * (0.3 + 0.7 * (i / count))
        const offsetX = Math.cos(angle) * distance * (area === 'right' ? 1 : -1)
        const offsetY = Math.sin(angle) * distance
        
        position = [
          baseCenter[0] + offsetX + (area === 'right' ? 0.003 : -0.003),
          baseCenter[1] + offsetY
        ]
        
        // 检查与已有位置的距离
        const tooClose = positions.some(pos => {
          const dx = pos[0] - position[0]
          const dy = pos[1] - position[1]
          return Math.sqrt(dx * dx + dy * dy) < minDistance
        })
        
        if (!tooClose || attempts > 10) break
        attempts++
      } while (attempts <= 10)
      
      positions.push(position)
    }
    
    return positions
  }

  // 地图显示模式状态
  const [mapDisplayMode, setMapDisplayMode] = useState<'overview' | 'departments' | 'equipment' | 'alerts'>('overview')

  // 将真实数据转换为地图数据并更新地图
  const updateMapData = useCallback((data: ReturnType<typeof realDataService.getAllRealTimeData>) => {
    if (!mapViewerRef.current || !data) return
    
    try {
      // 清除现有的POI点位
      const existingPOIs = [...pois]
      existingPOIs.forEach(poi => {
        mapViewerRef.current?.removePOI?.(poi.id)
      })
      setPOIs([])
      
      const baseCenter = currentSite?.center || [120.1551, 30.2741]
      
      // 根据显示模式决定显示什么POI
      let poisToShow: POIData[] = []
      
      if (mapDisplayMode === 'overview') {
        // 概览模式：只显示医院主要入口和关键信息
        poisToShow = [
          {
            id: 'main_entrance',
            name: '医院主入口',
            type: 'entrance',
            position: [baseCenter[0], baseCenter[1] - 0.001],
            floor: 'L1',
            description: '医院主要出入口，24小时开放'
          },
          {
            id: 'emergency_entrance',
            name: '急诊入口',
            type: 'emergency',
            position: [baseCenter[0] - 0.002, baseCenter[1]],
            floor: 'L1',
            description: '24小时急诊服务入口'
          },
          {
            id: 'info_center',
            name: '咨询服务台',
            type: 'entrance',
            position: [baseCenter[0] + 0.001, baseCenter[1] - 0.0005],
            floor: 'L1',
            description: '导医咨询、挂号服务'
          }
        ]
      } else if (mapDisplayMode === 'departments') {
        // 科室模式：显示主要科室（限制数量避免拥挤）
        const majorDepartments = (data.departments || []).filter(dept => 
          ['急诊科', '心内科', '外科', '儿科', '妇产科', '骨科'].includes(dept.name)
        ).slice(0, 6)
        
        const deptPositions = generateNaturalPOILayout(majorDepartments.length, baseCenter, 'left')
        
        poisToShow = majorDepartments.map((dept: Department, index: number) => {
          const position = deptPositions[index] || [baseCenter[0] - 0.002, baseCenter[1]]
          
          return {
            id: `dept_${dept.id}`,
            name: dept.name,
            type: 'department',
            position: position,
            floor: dept.floor || 'L1',
            description: `负责人: ${dept.director || '未知'}, 电话: ${dept.phone || '未知'}`,
            metadata: {
              capacity: dept.capacity,
              currentPatients: dept.currentPatients,
              waitingTime: dept.waitingTime,
              utilizationRate: dept.utilizationRate
            }
          }
        })
      } else if (mapDisplayMode === 'equipment') {
        // 设备模式：显示重要医疗设备
        const majorEquipment = (data.equipment || []).filter(equip => 
          ['CT', 'MRI', 'X光机', '手术台', '呼吸机', '监护仪'].some(type => equip.name.includes(type))
        ).slice(0, 8)
        
        const equipPositions = generateNaturalPOILayout(majorEquipment.length, baseCenter, 'right')
        
        poisToShow = majorEquipment.map((equip: Equipment, index: number) => {
          const position = equipPositions[index] || [baseCenter[0] + 0.002, baseCenter[1]]
          
          return {
            id: `equip_${equip.id}`,
            name: equip.name,
            type: 'equipment',
            position: position,
            floor: equip.location.includes('L') ? equip.location.split(' ')[0] : 'L1',
            description: `状态: ${equip.status}, 使用率: ${equip.currentUtilization}%`,
            metadata: {
              type: equip.type,
              status: equip.status,
              uptime: equip.uptime,
              maintenance: equip.maintenance,
              currentUtilization: equip.currentUtilization
            }
          }
        })
      } else if (mapDisplayMode === 'alerts') {
        // 告警模式：显示活跃告警
        const activeAlerts = (data.alerts || []).filter((alert: Alert) => alert.status === 'active')
        
        poisToShow = activeAlerts.map((alert: Alert, index: number) => {
          const angle = (index / activeAlerts.length) * 2 * Math.PI
          const radius = 0.002
          const offsetX = Math.cos(angle) * radius
          const offsetY = Math.sin(angle) * radius
          
          return {
            id: `alert_${alert.id}`,
            name: alert.title,
            type: 'emergency',
            position: [baseCenter[0] + offsetX, baseCenter[1] + offsetY],
            floor: 'L1',
            description: alert.description,
            metadata: {
              severity: alert.severity,
              status: alert.status,
              location: alert.location,
              timestamp: alert.timestamp
            }
          }
        })
      }
      
      // 添加POI到地图
      poisToShow.forEach(poi => {
        mapViewerRef.current?.addPOI?.(poi)
      })
      
      // 更新状态
      setPOIs(poisToShow)
      
      console.log('地图数据更新完成:', {
        mode: mapDisplayMode,
        poisShown: poisToShow.length,
        totalAvailable: {
          departments: data.departments?.length || 0,
          equipment: data.equipment?.length || 0,
          alerts: data.alerts?.length || 0
        }
      })
      
      // 如果切换到概览模式，自动调整地图视角
      if (mapDisplayMode === 'overview') {
        setTimeout(() => {
          mapViewerRef.current?.flyTo?.(baseCenter, DEFAULT_ZOOM)
        }, 500)
      }
      
    } catch (error) {
      console.error('更新地图数据失败:', error)
    }
  }, [currentSite, pois, mapDisplayMode])
  
  // 旧的详细显示方法（保留作为备用）
  // const updateMapDataDetailed = useCallback((data: ReturnType<typeof realDataService.getAllRealTimeData>) => {
  //   if (!mapViewerRef.current || !data) return
  //   
  //   try {
  //     // 清除现有的POI点位
  //     const existingPOIs = [...pois]
  //     existingPOIs.forEach(poi => {
  //       mapViewerRef.current?.removePOI?.(poi.id)
  //     })
  //     setPOIs([])
  //     
  //     const baseCenter = currentSite?.center || [120.1551, 30.2741]
  //     
  //     // 生成科室和设备的布局位置
  //     const deptPositions = generateNaturalPOILayout(data.departments?.length || 0, baseCenter, 'left')
  //     const equipPositions = generateNaturalPOILayout(data.equipment?.length || 0, baseCenter, 'right')
  //     
  //     // 1. 将科室数据转换为POI点位
  //     const departmentPOIs: POIData[] = (data.departments || []).map((dept: Department, index: number) => {
  //       const position = deptPositions[index] || [baseCenter[0] - 0.002, baseCenter[1]]
  //       
  //       return {
  //         id: `dept_${dept.id}`,
  //         name: dept.name,
  //         type: 'department',
  //         position: position,
  //         floor: dept.floor || 'L1',
  //         description: `负责人: ${dept.director || '未知'}, 电话: ${dept.phone || '未知'}`,
  //         metadata: {
  //           capacity: dept.capacity,
  //           currentPatients: dept.currentPatients,
  //           waitingTime: dept.waitingTime,
  //           utilizationRate: dept.utilizationRate
  //         }
  //       }
  //     })
  //     
  //     // 2. 将设备数据转换为POI点位
  //     const equipmentPOIs: POIData[] = (data.equipment || []).map((equip: Equipment, index: number) => {
  //       const position = equipPositions[index] || [baseCenter[0] + 0.002, baseCenter[1]]
  //       
  //       return {
  //         id: `equip_${equip.id}`,
  //         name: equip.name,
  //         type: 'equipment',
  //         position: position,
  //         floor: equip.location.includes('L') ? equip.location.split(' ')[0] : 'L1',
  //         description: `状态: ${equip.status}, 使用率: ${equip.currentUtilization}%`,
  //         metadata: {
  //           type: equip.type,
  //           status: equip.status,
  //           uptime: equip.uptime,
  //           maintenance: equip.maintenance,
  //           currentUtilization: equip.currentUtilization
  //         }
  //       }
  //     })
  //     
  //     // 3. 将告警数据转换为POI点位（紧急告警）
  //     const alertPOIs: POIData[] = (data.alerts || [])
  //       .filter((alert: Alert) => alert.severity === 'high' && alert.status === 'active')
  //       .map((alert: Alert, index: number) => {
  //         // 计算告警在地图上的位置
  //         const baseCenter = currentSite?.center || [120.1551, 30.2741]
  //         const offsetX = (index % 3) * 0.0003 - 0.0015
  //         const offsetY = Math.floor(index / 3) * 0.0003 + 0.0015
  //         
  //         return {
  //           id: `alert_${alert.id}`,
  //           name: alert.title,
  //           type: 'emergency',
  //           position: [baseCenter[0] + offsetX, baseCenter[1] + offsetY],
  //           floor: 'L1', // 假设告警都在一楼
  //           description: alert.description,
  //           metadata: {
  //             severity: alert.severity,
  //             status: alert.status,
  //             location: alert.location,
  //             timestamp: alert.timestamp
  //           }
  //         }
  //       })
  //     
  //     // 4. 合并所有POI点位
  //     const allPOIs = [...departmentPOIs, ...equipmentPOIs, ...alertPOIs]
  //     
  //     // 5. 将POI点位添加到地图上
  //     allPOIs.forEach(poi => {
  //       mapViewerRef.current?.addPOI?.(poi)
  //     })
  //     
  //     // 更新状态
  //     setPOIs(allPOIs)
  //     
  //     // 6. 可选：如果有高优先级告警，自动定位到第一个告警位置
  //     const highPriorityAlerts = alertPOIs.filter(poi => 
  //       poi.metadata?.severity === 'high' && poi.metadata?.status === 'active'
  //     )
  //     
  //     if (highPriorityAlerts.length > 0) {
  //       const firstAlert = highPriorityAlerts[0]
  //       mapViewerRef.current?.flyTo?.(firstAlert.position, 18)
  //       toast.info(`发现${highPriorityAlerts.length}个高优先级告警，已自动定位到: ${firstAlert.name}`)
  //     }
  //     
  //     console.log('地图数据更新完成:', {
  //       departments: departmentPOIs.length,
  //       equipment: equipmentPOIs.length,
  //       alerts: alertPOIs.length
  //     })
  //   } catch (error) {
  //     console.error('更新地图数据失败:', error)
  //     toast.error('更新地图数据失败，请检查控制台获取详细信息')
  //   }
  // }, [currentSite, pois, mapViewerRef])
  
  // 加载医院数据
  const [hospitalData, setHospitalData] = useState<{
    hospitals: Array<{ id: string; name: string; address?: string; center?: [number, number] }>
    buildings: Array<{ id: string; hospitalId: string; name: string }>
    departments: Array<{ id: string; hospitalId: string; name: string; type: string; status: string; capacity?: number }>
    equipment: Array<{ id: string; hospitalId: string; name: string; type: string; status: string }>
  }>({
    hospitals: [],
    buildings: [],
    departments: [],
    equipment: []
  })

  // 加载医院管理系统数据
  useEffect(() => {
    const loadHospitalData = async () => {
      try {
        console.log('仪表盘: 开始加载医院数据...')
        
        // 优先尝试从真实API获取医院数据
        let hospitals = []
        try {
          const hospitalAPI = await import('@/lib/api/hospital')
          const response = await hospitalAPI.hospitalAPI.getSites({
            status: 'active',
            limit: 100
          })
          
          if (response?.success && response?.data?.sites) {
            hospitals = response.data.sites.map((site: any) => ({
              id: site.siteId,
              name: site.name,
              address: site.address,
              center: [site.coordinates.longitude, site.coordinates.latitude],
              zoom: site.zoom || 16,
              city: site.city,
              province: site.province
            }))
            console.log('仪表盘: 成功从API获取医院数据:', hospitals.length)
          }
        } catch (apiError) {
          console.warn('仪表盘: API获取失败，尝试从IndexedDB获取:', apiError)
        }
        
        // 如果API获取失败，回退到IndexedDB
        if (hospitals.length === 0) {
          hospitals = await hospitalDB.getHospitals()
          console.log('仪表盘: 从IndexedDB获取医院数据:', hospitals?.length || 0)
        }
        
        const [allBuildings, allDepartments, allEquipment] = await Promise.all([
          hospitalDB.getHospitalBuildings(),
          hospitalDB.getAll('departments'),
          hospitalDB.getAll('medical_equipment')
        ])
        
        console.log('仪表盘: 医院数据加载结果:', {
          hospitals: hospitals?.length || 0,
          buildings: allBuildings?.length || 0,
          departments: allDepartments?.length || 0,
          equipment: allEquipment?.length || 0
        })
        
        setHospitalData({
          hospitals: hospitals || [],
          buildings: allBuildings || [],
          departments: allDepartments || [],
          equipment: allEquipment || []
        })
        
        // 如果有数据，设置到地图上
        if (hospitals && hospitals.length > 0) {
          setCurrentSiteId(hospitals[0].id)
          const hospital = hospitals[0]
          setCurrentSite({
            id: hospital.id,
            name: hospital.name,
            center: hospital.center || DEFAULT_CENTER,
            zoom: DEFAULT_ZOOM,
            address: hospital.address
          })
        }
        
      } catch (error) {
        console.error('仪表盘: 加载医院数据失败:', error)
        toast.error('加载医院数据失败')
      }
    }
    
    // 延迟加载以确保IndexedDB初始化完成
    const timer = setTimeout(() => {
      loadHospitalData()
    }, 1000)
    
    return () => clearTimeout(timer)
  }, [])

  // 初始化真实数据并设置自动更新
  useEffect(() => {
    // 立即加载一次数据
    const data = realDataService.getAllRealTimeData()
    setRealTimeData(data)
    
    // 将数据展示到地图上
    updateMapData(data)
    
    // 设置定时更新 (每30秒)
    const interval = setInterval(() => {
      const newData = realDataService.getAllRealTimeData()
      setRealTimeData(newData)
      
      // 更新地图数据
      updateMapData(newData)
    }, 30000)
    
    return () => clearInterval(interval)
  }, [updateMapData])

  // 初始化站点数据 - 从API获取
  useEffect(() => {
    if (!isMounted) return
    
    const loadSitesFromAPI = async () => {
      try {
        const { hospitalAPI } = await import('@/lib/api/hospital')
        const response = await hospitalAPI.getSites({
          status: 'active',
          limit: 100
        })
        
        if (response?.success && response?.data?.sites) {
          const apiSites = response.data.sites.map((site: any) => ({
            id: site.siteId,
            name: site.name,
            center: [site.coordinates.longitude, site.coordinates.latitude] as [number, number],
            zoom: site.zoom || 16,
            address: site.address,
            district: site.district,
            city: site.city,
            province: site.province
          }))
          
          setSites(apiSites)
          
          // 尝试恢复之前选中的站点
          const savedCurrentSiteId = localStorage.getItem('current_site_id')
          if (savedCurrentSiteId && apiSites.find((s: any) => s.id === savedCurrentSiteId)) {
            setCurrentSiteId(savedCurrentSiteId)
          } else if (apiSites.length > 0) {
            setCurrentSiteId(apiSites[0].id)
          }
          
          console.log('从API加载医院站点:', apiSites.length)
        }
      } catch (error) {
        console.error('从API加载站点数据失败，尝试从localStorage获取:', error)
        
        // 如果API失败，回退到localStorage
        try {
          const savedSites = localStorage.getItem('hospital_sites')
          if (savedSites) {
            const parsedSites: HospitalSite[] = JSON.parse(savedSites)
            setSites(parsedSites)
            
            const savedCurrentSiteId = localStorage.getItem('current_site_id')
            if (savedCurrentSiteId && parsedSites.find(s => s.id === savedCurrentSiteId)) {
              setCurrentSiteId(savedCurrentSiteId)
            } else if (parsedSites.length > 0) {
              setCurrentSiteId(parsedSites[0].id)
            }
          }
        } catch (localError) {
          console.error('从localStorage加载站点数据也失败:', localError)
          localStorage.removeItem('hospital_sites')
          localStorage.removeItem('current_site_id')
        }
      }
    }
    
    loadSitesFromAPI()
  }, [isMounted])

  // 登出功能
  // 重复定义已移除，使用前部统一实现的 handleLogout

  // 获取角色显示名称
  const getRoleDisplayName = (role: UserRole | string) => {
    if (!isMounted) return '' // 客户端挂载前返回空字符串
    
    // 角色映射，确保兼容性
    const normalizeRole = (inputRole: string | UserRole): UserRole => {
      if (typeof inputRole === 'string') {
        const roleMapping: { [k: string]: UserRole } = {
          'admin': UserRole.SUPER_ADMIN,
          'super_admin': UserRole.SUPER_ADMIN,
          'dean': UserRole.DEAN,
          'director': UserRole.DIRECTOR,
          'doctor': UserRole.DOCTOR,
          'nurse': UserRole.NURSE,
          'user': UserRole.DOCTOR,
          'manager': UserRole.DEAN,
          'guide': UserRole.NURSE,
          'security': UserRole.DOCTOR
        }
        return roleMapping[inputRole] || UserRole.DOCTOR
      }
      return inputRole as UserRole
    }
    
    const normalizedRole = normalizeRole(role as string)
    
    // 安全检查：确保role存在且在RoleDisplayNames中有定义
    if (!normalizedRole || !RoleDisplayNames[normalizedRole]) {
      console.warn('[Dashboard] 未知角色:', role, '-> 规范化后:', normalizedRole)
      return '未知角色'
    }
    
    return locale === 'zh-CN'
      ? RoleDisplayNames[normalizedRole].zh
      : RoleDisplayNames[normalizedRole].en
  }

  // 检查用户是否可以访问特定Tab
  const canAccessTab = useCallback((tab: string) => {
    // 在客户端挂载前，只显示基本的dashboard tab以避免水合错误
    if (!isMounted) {
      return tab === 'dashboard'
    }

    const tabPermissionMap: Record<string, string> = {
      'dashboard': 'dashboard',
      'monitoring': 'realtime',
      'analytics': 'analytics',
      'optimization': 'optimization',
        'scenarios': 'scenarios',
        'management': 'dashboard', // 管理中心所有角色都可访问，但内容不同
        'ocr': 'dashboard' // OCR功能所有角色都可访问
    }

    const page = tabPermissionMap[tab]
    // 修复：传递用户ID以支持自定义权限检查
    return page ? PermissionChecker.canAccessPage(currentUserRole, page, currentUser?.id) : false
  }, [isMounted, currentUserRole, currentUser?.id])

  // 当角色变化时，自动切换到第一个有权限的Tab
  useEffect(() => {
    if (!isMounted) return

    // 将getAccessibleTabs移到useEffect内部以避免依赖问题
    const getAccessibleTabsInner = () => {
      // 在客户端挂载前，只返回dashboard以避免水合错误
      if (!isMounted) {
        return ['dashboard']
      }

      // 基础tabs对所有角色开放
      const allTabs = ['dashboard', 'monitoring', 'analytics', 'optimization', 'scenarios', 'management', 'hospital-map', 'ocr']

      return allTabs.filter(tab => canAccessTab(tab))
    }

    const accessibleTabs = getAccessibleTabsInner()
    if (accessibleTabs.length > 0 && !accessibleTabs.includes(selectedTab)) {
      setSelectedTab(accessibleTabs[0])
    }
  }, [currentUserRole, isMounted, selectedTab, canAccessTab])

  // 响应式工具函数 - 使用useMemo优化
  // const getResponsiveGridCols = useMemo(() => (baseGridCols: number) => {
  //   switch (screenSize) {
  //     case 'sm': return Math.min(baseGridCols, 1)
  //     case 'md': return Math.min(baseGridCols, 2)
  //     case 'lg': return Math.min(baseGridCols, 3)
  //     case 'xl': return Math.min(baseGridCols, 4)
  //     case '2xl': return baseGridCols
  //     default: return baseGridCols
  //   }
  // }, [screenSize])

  const getResponsiveCardPadding = useMemo(() => {
    return screenSize === 'sm' ? 'p-3' : screenSize === 'md' ? 'p-4' : 'p-6'
  }, [screenSize])

  const getResponsiveFontSize = useMemo(() => (base: string) => {
    switch (base) {
      case 'title':
        return screenSize === 'sm' ? 'text-lg' : screenSize === 'md' ? 'text-xl' : 'text-2xl'
      case 'metric':
        return screenSize === 'sm' ? 'text-xl' : screenSize === 'md' ? 'text-2xl' : 'text-3xl'
      case 'label':
        return screenSize === 'sm' ? 'text-xs' : 'text-sm'
      default:
        return base
    }
  }, [screenSize])

  const shouldShowSidebar = () => {
    return !isSidebarCollapsed && (selectedTab === 'monitoring' || selectedTab === 'analytics')
  }

  // const getMobileOptimizedStyles = () => {
  //   if (isMobile) {
  //     return {
  //       cardPadding: 'p-2',
  //       fontSize: 'text-sm',
  //       iconSize: 'w-4 h-4',
  //       spacing: 'space-x-1 space-y-1',
  //       buttonSize: 'px-2 py-1 text-xs'
  //     }
  //   } else if (isTablet) {
  //     return {
  //       cardPadding: 'p-3',
  //       fontSize: 'text-base',
  //       iconSize: 'w-5 h-5',
  //       spacing: 'space-x-2 space-y-2',
  //       buttonSize: 'px-3 py-1.5 text-sm'
  //     }
  //   }
  //   return {
  //     cardPadding: 'p-4',
  //     fontSize: 'text-base',
  //     iconSize: 'w-6 h-6',
  //     spacing: 'space-x-3 space-y-3',
  //     buttonSize: 'px-4 py-2 text-base'
  //   }
  // }

  // const getScaledSize = (baseSize: number) => {
  //   return Math.round(baseSize * scaleFactor)
  // }

  // const getScaledFontClass = (base: string) => {
  //   const sizeMap: Record<string, number> = {
  //     'text-xs': 12,
  //     'text-sm': 14,
  //     'text-base': 16,
  //     'text-lg': 18,
  //     'text-xl': 20,
  //     'text-2xl': 24,
  //     'text-3xl': 30,
  //     'text-4xl': 36
  //   }
  //   
  //   const baseSize = sizeMap[base] || 16
  //   const scaledSize = getScaledSize(baseSize)
  //   
  //   if (scaledSize <= 12) return 'text-xs'
  //   if (scaledSize <= 14) return 'text-sm'
  //   if (scaledSize <= 16) return 'text-base'
  //   if (scaledSize <= 18) return 'text-lg'
  //   if (scaledSize <= 20) return 'text-xl'
  //   if (scaledSize <= 24) return 'text-2xl'
  //   if (scaledSize <= 30) return 'text-3xl'
  //   return 'text-4xl'
  // }

  // const getScaledIconClass = (baseClass: string) => {
  //   const sizeMatch = baseClass.match(/w-(\d+)\s+h-(\d+)/)
  //   if (!sizeMatch) return baseClass
  //   
  //   const baseSize = parseInt(sizeMatch[1])
  //   const scaledSize = getScaledSize(baseSize * 4) // Convert to pixels then scale
  //   const finalSize = Math.round(scaledSize / 4) // Convert back to Tailwind units
  //   
  //   return `w-${Math.max(3, Math.min(12, finalSize))} h-${Math.max(3, Math.min(12, finalSize))}`
  // }

  // getAccessibleTabs已移至useEffect内部

  // 基于角色的仪表板内容渲染
  const renderRoleBasedDashboard = () => {
    switch (currentUserRole) {
      case UserRole.NURSE:
        // 护士：关注患者护理和设备状态
        return (
          <div className="space-y-6">
            <div className="mb-6">
              <h2 className="text-2xl font-bold text-gray-900 mb-2">护理工作台</h2>
              <p className="text-gray-600">今日护理任务和患者状态监控</p>
            </div>

            {/* 护士专用KPI */}
            <div className={`grid gap-3 md:gap-4 lg:gap-6 ${
              screenSize === 'sm' ? 'grid-cols-1' : 
              screenSize === 'md' ? 'grid-cols-2' : 
              'grid-cols-3'
            }`}>
              <Card className="metric-card border-pink-200 bg-pink-50">
                <CardContent className={getResponsiveCardPadding}>
                  <div className="flex items-center justify-between">
                    <div>
                      <p className={`${getResponsiveFontSize('label')} text-pink-600`}>今日护理患者</p>
                      <p className={`${getResponsiveFontSize('metric')} font-bold text-pink-700`}>28</p>
                      <p className="text-xs text-pink-500">待护理: 5人</p>
                    </div>
                    <IconUsers className={`${screenSize === 'sm' ? 'w-6 h-6' : 'w-8 h-8'} text-pink-500`} />
                  </div>
                </CardContent>
              </Card>

              <Card className="metric-card border-green-200 bg-green-50">
                <CardContent className={getResponsiveCardPadding}>
                  <div className="flex items-center justify-between">
                    <div>
                      <p className={`${getResponsiveFontSize('label')} text-green-600`}>药物配发</p>
                      <p className={`${getResponsiveFontSize('metric')} font-bold text-green-700`}>156</p>
                      <p className="text-xs text-green-500">已完成: 142</p>
                    </div>
                    <IconActivity className={`${screenSize === 'sm' ? 'w-6 h-6' : 'w-8 h-8'} text-green-500`} />
                  </div>
                </CardContent>
              </Card>

              <Card className="metric-card border-orange-200 bg-orange-50">
                <CardContent className={getResponsiveCardPadding}>
                  <div className="flex items-center justify-between">
                    <div>
                      <p className={`${getResponsiveFontSize('label')} text-orange-600`}>设备检查</p>
                      <p className={`${getResponsiveFontSize('metric')} font-bold text-orange-700`}>12</p>
                      <p className="text-xs text-orange-500">异常: 2台</p>
                    </div>
                    <IconBed className={`${screenSize === 'sm' ? 'w-6 h-6' : 'w-8 h-8'} text-orange-500`} />
                  </div>
                </CardContent>
              </Card>
            </div>

            {/* 今日任务 */}
            <Card>
              <CardHeader>
                <CardTitle>今日护理任务</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-3">
                  {[
                    { patient: "张三", room: "301", task: "药物注射", time: "09:00", status: "completed" },
                    { patient: "李四", room: "302", task: "生命体征检查", time: "10:30", status: "pending" },
                    { patient: "王五", room: "303", task: "伤口换药", time: "14:00", status: "pending" }
                  ].map((task, index) => (
                    <div key={index} className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                      <div>
                        <p className="font-medium">{task.patient} - {task.room}床</p>
                        <p className="text-sm text-gray-600">{task.task}</p>
                      </div>
                      <div className="text-right">
                        <p className="text-sm text-gray-500">{task.time}</p>
                        <Badge variant={task.status === 'completed' ? 'default' : 'secondary'}>
                          {task.status === 'completed' ? '已完成' : '待处理'}
                        </Badge>
                      </div>
                    </div>
                  ))}
                </div>
              </CardContent>
            </Card>
          </div>
        )

      case UserRole.DOCTOR:
        // 医生：关注患者诊疗和临床数据
        return (
          <div className="space-y-6">
            <div className="mb-6">
              <h2 className="text-2xl font-bold text-gray-900 mb-2">医生工作台</h2>
              <p className="text-gray-600">患者诊疗和临床决策支持</p>
            </div>

            {/* 医生专用KPI */}
            <div className={`grid gap-3 md:gap-4 lg:gap-6 ${
              screenSize === 'sm' ? 'grid-cols-1' : 
              screenSize === 'md' ? 'grid-cols-2' : 
              'grid-cols-4'
            }`}>
              <Card className="metric-card border-blue-200 bg-blue-50">
                <CardContent className={getResponsiveCardPadding}>
                  <div className="flex items-center justify-between">
                    <div>
                      <p className={`${getResponsiveFontSize('label')} text-blue-600`}>今日门诊</p>
                      <p className={`${getResponsiveFontSize('metric')} font-bold text-blue-700`}>32</p>
                      <p className="text-xs text-blue-500">剩余: 8人</p>
                    </div>
                    <IconUsers className={`${screenSize === 'sm' ? 'w-6 h-6' : 'w-8 h-8'} text-blue-500`} />
                  </div>
                </CardContent>
              </Card>

              <Card className="metric-card border-green-200 bg-green-50">
                <CardContent className="p-6">
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="text-sm text-green-600">住院患者</p>
                      <p className="text-2xl font-bold text-green-700">15</p>
                      <p className="text-xs text-green-500">重症: 3人</p>
                    </div>
                    <IconBed className="w-8 h-8 text-green-500" />
                  </div>
                </CardContent>
              </Card>

              <Card className="metric-card border-purple-200 bg-purple-50">
                <CardContent className="p-6">
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="text-sm text-purple-600">检查报告</p>
                      <p className="text-2xl font-bold text-purple-700">24</p>
                      <p className="text-xs text-purple-500">待审阅: 6份</p>
                    </div>
                    <IconChartBar className="w-8 h-8 text-purple-500" />
                  </div>
                </CardContent>
              </Card>

              <Card className="metric-card border-red-200 bg-red-50">
                <CardContent className="p-6">
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="text-sm text-red-600">紧急会诊</p>
                      <p className="text-2xl font-bold text-red-700">3</p>
                      <p className="text-xs text-red-500">待处理: 1个</p>
                    </div>
                    <IconAlertTriangle className="w-8 h-8 text-red-500" />
                  </div>
                </CardContent>
              </Card>
            </div>

            {/* 患者优先级列表 */}
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
              <Card>
                <CardHeader>
                  <CardTitle>高优先级患者</CardTitle>
                </CardHeader>
                <CardContent>
                  <div className="space-y-3">
                    {[
                      { name: "赵六", condition: "急性心梗", priority: "critical", room: "ICU-01" },
                      { name: "孙七", condition: "呼吸困难", priority: "high", room: "302" },
                      { name: "周八", condition: "术后观察", priority: "medium", room: "305" }
                    ].map((patient, index) => (
                      <div key={index} className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                        <div>
                          <p className="font-medium">{patient.name} - {patient.room}</p>
                          <p className="text-sm text-gray-600">{patient.condition}</p>
                        </div>
                        <Badge variant={
                          patient.priority === 'critical' ? 'destructive' :
                            patient.priority === 'high' ? 'secondary' : 'default'
                        }>
                          {patient.priority === 'critical' ? '紧急' :
                            patient.priority === 'high' ? '重要' : '一般'}
                        </Badge>
                      </div>
                    ))}
                  </div>
                </CardContent>
              </Card>

              <Card>
                <CardHeader>
                  <CardTitle>今日手术安排</CardTitle>
                </CardHeader>
                <CardContent>
                  <div className="space-y-3">
                    {[
                      { patient: "李四", surgery: "阑尾切除术", time: "14:00", room: "手术室2" },
                      { patient: "王五", surgery: "胆囊切除术", time: "16:30", room: "手术室1" }
                    ].map((surgery, index) => (
                      <div key={index} className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                        <div>
                          <p className="font-medium">{surgery.patient}</p>
                          <p className="text-sm text-gray-600">{surgery.surgery}</p>
                        </div>
                        <div className="text-right">
                          <p className="text-sm font-medium">{surgery.time}</p>
                          <p className="text-xs text-gray-500">{surgery.room}</p>
                        </div>
                      </div>
                    ))}
                  </div>
                </CardContent>
              </Card>
            </div>
          </div>
        )

      case UserRole.DIRECTOR:
        // 主任：关注科室管理和资源调配
        return (
          <div className="space-y-6">
            <div className="mb-6">
              <h2 className="text-2xl font-bold text-gray-900 mb-2">科室管理中心</h2>
              <p className="text-gray-600">科室运营状况和资源配置管理</p>
            </div>

            {/* 主任专用KPI */}
            <div className="grid grid-cols-1 md:grid-cols-4 gap-6">
              <Card className="metric-card border-indigo-200 bg-indigo-50">
                <CardContent className="p-6">
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="text-sm text-indigo-600">科室效率</p>
                      <p className="text-2xl font-bold text-indigo-700">85%</p>
                      <p className="text-xs text-indigo-500">较昨日: +2%</p>
                    </div>
                    <IconActivity className="w-8 h-8 text-indigo-500" />
                  </div>
                </CardContent>
              </Card>

              <Card className="metric-card border-cyan-200 bg-cyan-50">
                <CardContent className="p-6">
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="text-sm text-cyan-600">医生在岗</p>
                      <p className="text-2xl font-bold text-cyan-700">12/15</p>
                      <p className="text-xs text-cyan-500">请假: 3人</p>
                    </div>
                    <IconUsers className="w-8 h-8 text-cyan-500" />
                  </div>
                </CardContent>
              </Card>

              <Card className="metric-card border-emerald-200 bg-emerald-50">
                <CardContent className="p-6">
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="text-sm text-emerald-600">病床周转</p>
                      <p className="text-2xl font-bold text-emerald-700">3.2天</p>
                      <p className="text-xs text-emerald-500">较上月: -0.5天</p>
                    </div>
                    <IconBed className="w-8 h-8 text-emerald-500" />
                  </div>
                </CardContent>
              </Card>

              <Card className="metric-card border-amber-200 bg-amber-50">
                <CardContent className="p-6">
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="text-sm text-amber-600">质量指标</p>
                      <p className="text-2xl font-bold text-amber-700">92分</p>
                      <p className="text-xs text-amber-500">目标: 95分</p>
                    </div>
                    <IconTarget className="w-8 h-8 text-amber-500" />
                  </div>
                </CardContent>
              </Card>
            </div>

            {/* 科室概况 */}
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
              <Card>
                <CardHeader>
                  <CardTitle>科室人员状态</CardTitle>
                </CardHeader>
                <CardContent>
                  <div className="space-y-3">
                    {[
                      { name: "张医生", status: "门诊中", patients: 8, shift: "白班" },
                      { name: "李医生", status: "手术中", patients: 0, shift: "白班" },
                      { name: "王医生", status: "查房", patients: 12, shift: "白班" },
                      { name: "赵医生", status: "休息", patients: 0, shift: "夜班" }
                    ].map((doctor, index) => (
                      <div key={index} className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                        <div>
                          <p className="font-medium">{doctor.name}</p>
                          <p className="text-sm text-gray-600">{doctor.shift} - 负责患者: {doctor.patients}人</p>
                        </div>
                        <Badge variant={
                          doctor.status === '门诊中' ? 'default' :
                            doctor.status === '手术中' ? 'destructive' :
                              doctor.status === '查房' ? 'secondary' : 'outline'
                        }>
                          {doctor.status}
                        </Badge>
                      </div>
                    ))}
                  </div>
                </CardContent>
              </Card>

              <Card>
                <CardHeader>
                  <CardTitle>资源配置状况</CardTitle>
                </CardHeader>
                <CardContent>
                  <div className="space-y-4">
                    <div>
                      <div className="flex justify-between text-sm mb-1">
                        <span>病床占用率</span>
                        <span>28/32 (87.5%)</span>
                      </div>
                      <Progress value={87.5} className="w-full" />
                    </div>
                    <div>
                      <div className="flex justify-between text-sm mb-1">
                        <span>设备使用率</span>
                        <span>良好 (91%)</span>
                      </div>
                      <Progress value={91} className="w-full" />
                    </div>
                    <div>
                      <div className="flex justify-between text-sm mb-1">
                        <span>护理人员配比</span>
                        <span>1:4 (标准)</span>
                      </div>
                      <Progress value={100} className="w-full" />
                    </div>
                  </div>
                </CardContent>
              </Card>
            </div>
          </div>
        )

      case UserRole.DEAN:
      case UserRole.SUPER_ADMIN:
        // 院长/超级管理员：全局视图和战略决策
        return (
          <div className="space-y-6">
            <div className="mb-6">
              <h2 className="text-2xl font-bold text-gray-900 mb-2">
                {currentUserRole === UserRole.SUPER_ADMIN ? '系统管理中心' : '院长管理中心'}
              </h2>
              <p className="text-gray-600">医院整体运营状况和战略决策支持</p>
            </div>

            {/* 全局KPI */}
            <div className="grid grid-cols-1 md:grid-cols-4 gap-6">
              <Card className="metric-card border-violet-200 bg-violet-50">
                <CardContent className="p-6">
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="text-sm text-violet-600">医院数量</p>
                      <p className="text-2xl font-bold text-violet-700">{hospitalData.hospitals.length}</p>
                      <div className="flex items-center mt-1">
                        <span className="text-xs text-violet-600">已接入医院</span>
                      </div>
                    </div>
                    <IconBed className="w-8 h-8 text-violet-500" />
                  </div>
                </CardContent>
              </Card>

              <Card className="metric-card border-blue-200 bg-blue-50">
                <CardContent className="p-6">
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="text-sm text-blue-600">医院建筑</p>
                      <p className="text-2xl font-bold text-blue-700">{hospitalData.buildings.length}</p>
                      <div className="flex items-center mt-1">
                        <span className="text-xs text-blue-600">建筑总数</span>
                      </div>
                    </div>
                    <IconUsers className="w-8 h-8 text-blue-500" />
                  </div>
                </CardContent>
              </Card>

              <Card className="metric-card border-green-200 bg-green-50">
                <CardContent className="p-6">
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="text-sm text-green-600">科室数量</p>
                      <p className="text-2xl font-bold text-green-700">{hospitalData.departments.length}</p>
                      <div className="flex items-center mt-1">
                        <span className="text-xs text-green-600">医疗科室</span>
                      </div>
                    </div>
                    <IconChartBar className="w-8 h-8 text-green-500" />
                  </div>
                </CardContent>
              </Card>

              <Card className="metric-card border-orange-200 bg-orange-50">
                <CardContent className="p-6">
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="text-sm text-orange-600">医疗设备</p>
                      <p className="text-2xl font-bold text-orange-700">{hospitalData.equipment.length}</p>
                      <div className="flex items-center mt-1">
                        <span className="text-xs text-orange-600">设备总数</span>
                      </div>
                    </div>
                    <IconTarget className="w-8 h-8 text-orange-500" />
                  </div>
                </CardContent>
              </Card>
            </div>

            {/* 各科室状况概览 */}
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
              <Card>
                <CardHeader>
                  <CardTitle>医院科室概览</CardTitle>
                  <CardDescription>
                    {hospitalData.departments.length > 0 
                      ? `共 ${hospitalData.departments.length} 个科室` 
                      : '暂无科室数据'}
                  </CardDescription>
                </CardHeader>
                <CardContent>
                  <div className="space-y-3">
                    {                      hospitalData.departments.length > 0 ? (
                      hospitalData.departments.slice(0, 5).map((dept) => (
                        <div key={dept.id} className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                          <div>
                            <p className="font-medium">{dept.name}</p>
                            <p className="text-sm text-gray-600">
                              类型: {dept.type === 'outpatient' ? '门诊' : 
                                    dept.type === 'inpatient' ? '住院' :
                                    dept.type === 'emergency' ? '急诊' :
                                    dept.type === 'surgery' ? '手术' :
                                    dept.type === 'laboratory' ? '检验' :
                                    dept.type === 'radiology' ? '影像' :
                                    dept.type === 'pharmacy' ? '药房' : '其他'}
                              {dept.capacity && ` | 容量: ${dept.capacity}人`}
                            </p>
                          </div>
                          <Badge variant={
                            dept.status === 'active' ? 'default' :
                            dept.status === 'inactive' ? 'secondary' : 'destructive'
                          }>
                            {dept.status === 'active' ? '运行中' :
                             dept.status === 'inactive' ? '停用' : '维护中'}
                          </Badge>
                        </div>
                      ))
                    ) : (
                      <div className="text-center py-6 text-gray-500">
                        <p className="text-sm">暂无科室数据</p>
                        <Button 
                          size="sm" 
                          className="mt-2" 
                          onClick={() => router.push('/hospital-management')}
                        >
                          前往管理中心添加科室
                        </Button>
                      </div>
                    )}
                    {hospitalData.departments.length > 5 && (
                      <div className="text-center pt-2">
                        <Button 
                          variant="outline" 
                          size="sm"
                          onClick={() => router.push('/hospital-management')}
                        >
                          查看全部 {hospitalData.departments.length} 个科室
                        </Button>
                      </div>
                    )}
                  </div>
                </CardContent>
              </Card>

              <Card>
                <CardHeader>
                  <CardTitle>医疗设备统计</CardTitle>
                  <CardDescription>
                    {hospitalData.equipment.length > 0 
                      ? `共 ${hospitalData.equipment.length} 台设备` 
                      : '暂无设备数据'}
                  </CardDescription>
                </CardHeader>
                <CardContent>
                  {hospitalData.equipment.length > 0 ? (
                    <div className="space-y-4">
                      {/* 设备状态统计 */}
                      <div className="grid grid-cols-2 gap-4">
                        <div className="text-center p-3 bg-green-50 rounded-lg">
                          <div className="text-lg font-bold text-green-700">
                            {hospitalData.equipment.filter(e => e.status === 'active').length}
                          </div>
                          <div className="text-xs text-green-600">运行中</div>
                        </div>
                        <div className="text-center p-3 bg-orange-50 rounded-lg">
                          <div className="text-lg font-bold text-orange-700">
                            {hospitalData.equipment.filter(e => e.status === 'maintenance').length}
                          </div>
                          <div className="text-xs text-orange-600">维护中</div>
                        </div>
                      </div>
                      
                      {/* 设备类型分布 */}
                      <div className="space-y-2">
                        <h4 className="font-medium text-sm">设备类型分布</h4>
                        {['ct', 'mri', 'xray', 'ultrasound', 'bed', 'wheelchair'].map(type => {
                          const count = hospitalData.equipment.filter(e => e.type === type).length
                          if (count === 0) return null
                          
                          const typeNames: Record<string, string> = {
                            ct: 'CT设备',
                            mri: 'MRI设备', 
                            xray: 'X光机',
                            ultrasound: '超声设备',
                            bed: '病床',
                            wheelchair: '轮椅'
                          }
                          
                          return (
                            <div key={type} className="flex justify-between text-sm">
                              <span>{typeNames[type] || type}</span>
                              <span className="font-medium">{count}台</span>
                            </div>
                          )
                        })}
                      </div>
                      
                      <div className="text-center">
                        <Button 
                          variant="outline" 
                          size="sm"
                          onClick={() => router.push('/hospital-management')}
                        >
                          设备详细管理
                        </Button>
                      </div>
                    </div>
                  ) : (
                    <div className="text-center py-6 text-gray-500">
                      <p className="text-sm">暂无设备数据</p>
                      <Button 
                        size="sm" 
                        className="mt-2" 
                        onClick={() => router.push('/hospital-management')}
                      >
                        前往管理中心添加设备
                      </Button>
                    </div>
                  )}

                  {currentUserRole === UserRole.SUPER_ADMIN && (
                    <div className="mt-4 p-3 bg-blue-50 rounded-lg">
                      <p className="text-sm font-medium text-blue-700">系统管理员专用</p>
                      <p className="text-xs text-blue-600 mt-1">
                        数据来源: 医院管理系统 IndexedDB | 状态: 正常 | 权限: 最高
                      </p>
                    </div>
                  )}
                </CardContent>
              </Card>
            </div>

            {/* 超级管理员专用：用户管理 */}
            {currentUserRole === UserRole.SUPER_ADMIN && (
              <div className="mt-8">
                <AdvancedUserManagement />
              </div>
            )}
          </div>
        )

      default:
        return (
          <div className="text-center py-12">
            <p className="text-gray-500">角色权限配置中...</p>
          </div>
        )
    }
  }
  // 检查登录状态
  // 移除重复的登录检查，因为AuthGuard已经处理了

  // 更新时间
  // 已移除未使用的useEffect

  // 监听全屏状态变化
  useEffect(() => {
    const handleFullscreenChange = () => {
      const isFullscreenNow = !!document.fullscreenElement
      setIsFullscreen(isFullscreenNow)

      // 全屏时自动调整布局
      if (isFullscreenNow) {
        // 小屏幕时强制隐藏侧边栏
        if (screenSize === 'sm' || screenSize === 'md') {
          setIsSidebarCollapsed(true)
        }
        
        // 延迟一下确保DOM更新完成
        setTimeout(() => {
          window.dispatchEvent(new Event('resize'))
        }, 100)
      } else {
        // 退出全屏时恢复侧边栏状态
        if (screenSize === 'lg' || screenSize === 'xl' || screenSize === '2xl') {
          setIsSidebarCollapsed(false)
        }
      }
    }

    document.addEventListener('fullscreenchange', handleFullscreenChange)
    return () => document.removeEventListener('fullscreenchange', handleFullscreenChange)
  }, [screenSize])



  // 登出功能
  const handleLogout = () => {
    AuthManager.logout()
    router.push('/login')
  }

  const handleTabChange = (value: string) => {
    setSelectedTab(value)
    // 设置默认菜单
    if (value === 'monitoring') {
      setSelectedMenu('realtime')
    } else if (value === 'analytics') {
      setSelectedMenu('history')
    } else if (value === 'hospital-map') {
      setSelectedMenu('hospital-map')
    }
  }

  const handleMenuClick = (menuKey: string) => {
    setSelectedMenu(menuKey)
  }

  // 渲染菜单内容
  const renderMenuContent = () => {
    switch (selectedMenu) {
      case 'dashboard':
        return (
          <>
            {/* 基于角色的仪表板内容 */}
            {renderRoleBasedDashboard()}
          </>
        )

      case 'realtime':
        return (
          <>
            {/* 实时数据监控标题 */}
            <div className="mb-6">
              <h2 className="text-2xl font-bold text-gray-900 mb-2">实时数据监控</h2>
              <p className="text-gray-600">实时监控患者流量、设备状态和关键指标</p>
            </div>

            {/* 实时流量监控 */}
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
              <Card className="border border-gray-200">
                <CardHeader>
                  <CardTitle className="text-lg">患者流量实时监控</CardTitle>
                  <CardDescription>各科室实时患者数量</CardDescription>
                </CardHeader>
                <CardContent>
                  <div className="space-y-4">
                    {[
                      { dept: "急诊科", count: 45, trend: "+12", status: "high" },
                      { dept: "心内科", count: 28, trend: "+5", status: "medium" },
                      { dept: "外科", count: 32, trend: "-3", status: "medium" },
                      { dept: "儿科", count: 19, trend: "+8", status: "low" },
                      { dept: "妇产科", count: 15, trend: "+2", status: "low" }
                    ].map((item, index) => (
                      <div key={index} className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                        <div className="flex items-center space-x-3">
                          <div className={`w-3 h-3 rounded-full ${item.status === 'high' ? 'bg-red-500' :
                            item.status === 'medium' ? 'bg-yellow-500' : 'bg-green-500'
                            }`}></div>
                          <span className="font-medium">{item.dept}</span>
                        </div>
                        <div className="flex items-center space-x-3">
                          <span className="text-lg font-bold">{item.count}</span>
                          <span className={`text-sm ${item.trend.startsWith('+') ? 'text-green-600' : 'text-red-600'
                            }`}>
                            {item.trend}
                          </span>
                        </div>
                      </div>
                    ))}
                  </div>
                </CardContent>
              </Card>

              <Card className="border border-gray-200">
                <CardHeader>
                  <CardTitle className="text-lg">设备运行状态</CardTitle>
                  <CardDescription>关键医疗设备实时状态</CardDescription>
                </CardHeader>
                <CardContent>
                  <div className="space-y-4">
                    {[
                      { device: "CT扫描仪", status: "运行中", uptime: "98.5%", lastMaintenance: "15天前" },
                      { device: "MRI设备", status: "待机", uptime: "95.2%", lastMaintenance: "8天前" },
                      { device: "手术室设备", status: "运行中", uptime: "99.1%", lastMaintenance: "3天前" },
                      { device: "ICU监护仪", status: "运行中", uptime: "99.8%", lastMaintenance: "1天前" },
                      { device: "药房系统", status: "运行中", uptime: "97.3%", lastMaintenance: "12天前" }
                    ].map((item, index) => (
                      <div key={index} className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                        <div>
                          <p className="font-medium">{item.device}</p>
                          <p className="text-sm text-gray-500">运行时间: {item.uptime}</p>
                        </div>
                        <div className="text-right">
                          <Badge variant={item.status === '运行中' ? 'default' : 'secondary'}>
                            {item.status}
                          </Badge>
                          <p className="text-xs text-gray-500 mt-1">{item.lastMaintenance}</p>
                        </div>
                      </div>
                    ))}
                  </div>
                </CardContent>
              </Card>
            </div>

            {/* 实时热力图预览 */}
            <Card className="glass-card modern-shadow-hover">
              <CardHeader>
                <CardTitle className="text-lg flex items-center gap-2">
                  <IconMap className="w-5 h-5 text-blue-600" />
                  实时热力图预览
                </CardTitle>
                <CardDescription>当前楼层拥挤度分布</CardDescription>
              </CardHeader>
              <CardContent>
                <HeatmapChart />
              </CardContent>
            </Card>
          </>
        )

      case 'history':
        return (
          <>
            {/* 历史趋势分析标题 */}
            <div className="mb-6">
              <h2 className="text-2xl font-bold text-gray-900 mb-2">历史趋势分析</h2>
              <p className="text-gray-600">分析历史数据趋势和模式，识别周期性规律</p>
            </div>

            {/* 时间范围选择 */}
            <div className="mb-6">
              <Card className="border border-gray-200">
                <CardContent className="p-4">
                  <div className="flex items-center space-x-4">
                    <span className="text-sm font-medium text-gray-700">时间范围:</span>
                    <div className="flex space-x-2">
                      {['今日', '本周', '本月', '本季度', '本年'].map((period) => (
                        <Button key={period} variant="outline" size="sm">
                          {period}
                        </Button>
                      ))}
                    </div>
                  </div>
                </CardContent>
              </Card>
            </div>

            {/* 趋势图表区域 */}
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
              <Card className="glass-card modern-shadow-hover">
                <CardHeader>
                  <CardTitle className="text-lg flex items-center gap-2">
                    <IconTrendingUp className="w-5 h-5 text-green-600" />
                    患者流量趋势
                  </CardTitle>
                  <CardDescription>24小时患者流量变化</CardDescription>
                </CardHeader>
                <CardContent className="h-80">
                  <TrendChart />
                </CardContent>
              </Card>

              <Card className="glass-card modern-shadow-hover">
                <CardHeader>
                  <CardTitle className="text-lg flex items-center gap-2">
                    <IconActivity className="w-5 h-5 text-blue-600" />
                    科室利用率趋势
                  </CardTitle>
                  <CardDescription>各科室资源利用率变化</CardDescription>
                </CardHeader>
                <CardContent className="h-80">
                  <UtilizationChart />
                </CardContent>
              </Card>
            </div>
          </>
        )

      case 'hospital-map':
        return (
          <div className="h-full flex flex-col">
            <div className="mb-4">
              <h2 className="text-2xl font-bold text-gray-900 mb-2">医院地图管理</h2>
              <p className="text-gray-600">管理医院POI点位和商铺信息</p>
              
              {/* 站点选择器 */}
              <div className="mt-4 p-4 bg-gray-50 rounded-lg">
                <h3 className="text-lg font-semibold mb-3">医院站点选择</h3>
                <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
                  {/* 显示从医院管理系统加载的医院数据 */}
                  {hospitalData.hospitals.map((hospital) => (
                    <div
                      key={hospital.id}
                      className={`p-3 rounded-lg border cursor-pointer transition-all hover:scale-[1.02] ${
                        currentSiteId === hospital.id 
                          ? 'border-blue-500 bg-blue-50 shadow-md' 
                          : 'border-gray-200 bg-white hover:border-gray-300 hover:shadow-sm'
                      }`}
                      onClick={() => {
                        setCurrentSiteId(hospital.id)
                        setCurrentSite({
                          id: hospital.id,
                          name: hospital.name,
                          center: hospital.center || DEFAULT_CENTER,
                          zoom: DEFAULT_ZOOM,
                          address: hospital.address
                        })
                        toast.success(`已切换到: ${hospital.name}`)
                      }}
                    >
                      <div className="flex items-start justify-between">
                        <div className="flex-1">
                          <h4 className="font-medium text-gray-900">{hospital.name}</h4>
                          {hospital.address && (
                            <p className="text-sm text-gray-600 mt-1">{hospital.address}</p>
                          )}
                          <p className="text-xs text-gray-500 mt-1">
                            坐标: {(hospital.center?.[0] || DEFAULT_CENTER[0]).toFixed(4)}, {(hospital.center?.[1] || DEFAULT_CENTER[1]).toFixed(4)}
                          </p>
                          <div className="flex gap-2 mt-2">
                            <span className="text-xs bg-green-100 text-green-700 px-2 py-1 rounded">
                              建筑: {hospitalData.buildings.filter(b => b.hospitalId === hospital.id).length}
                            </span>
                            <span className="text-xs bg-blue-100 text-blue-700 px-2 py-1 rounded">
                              科室: {hospitalData.departments.filter(d => d.hospitalId === hospital.id).length}
                            </span>
                          </div>
                        </div>
                        {currentSiteId === hospital.id && (
                          <div className="ml-2">
                            <div className="w-3 h-3 bg-blue-500 rounded-full animate-pulse"></div>
                          </div>
                        )}
                      </div>
                    </div>
                  ))}
                  
                  {/* 如果没有医院数据，显示加载状态 */}
                  {hospitalData.hospitals.length === 0 && (
                    <div className="p-4 text-center text-gray-500">
                      <div className="animate-spin w-6 h-6 border-2 border-blue-500 border-t-transparent rounded-full mx-auto mb-2"></div>
                      <p className="text-sm">正在加载医院数据...</p>
                      <p className="text-xs mt-1">如果长时间未显示，请访问&quot;管理中心&quot;初始化数据</p>
                      <Button 
                        size="sm" 
                        className="mt-3" 
                        onClick={() => router.push('/hospital-management')}
                      >
                        前往医院管理中心
                      </Button>
                    </div>
                  )}
                  
                  {/* 传统站点数据（兼容性保留） */}
                  {sites.filter(site => !hospitalData.hospitals.find(h => h.id === site.id)).map((site) => (
                    <div
                      key={site.id}
                      className={`p-3 rounded-lg border cursor-pointer transition-all hover:scale-[1.02] ${
                        currentSiteId === site.id 
                          ? 'border-gray-400 bg-gray-50 shadow-md' 
                          : 'border-gray-200 bg-white hover:border-gray-300 hover:shadow-sm'
                      }`}
                      onClick={() => handleSiteSelect(site.id)}
                    >
                      <div className="flex items-start justify-between">
                        <div className="flex-1">
                          <h4 className="font-medium text-gray-900">{site.name}</h4>
                          {site.address && (
                            <p className="text-sm text-gray-600 mt-1">{site.address}</p>
                          )}
                          <p className="text-xs text-gray-500 mt-1">
                            坐标: {site.center[0].toFixed(4)}, {site.center[1].toFixed(4)}
                          </p>
                          <span className="text-xs bg-gray-100 text-gray-600 px-2 py-1 rounded mt-1 inline-block">
                            传统站点
                          </span>
                        </div>
                        {currentSiteId === site.id && (
                          <div className="ml-2">
                            <div className="w-3 h-3 bg-gray-500 rounded-full animate-pulse"></div>
                          </div>
                        )}
                      </div>
                    </div>
                  ))}
                  
                  {/* 添加新站点按钮 */}
                  <div 
                    className="p-3 rounded-lg border-2 border-dashed border-gray-300 cursor-pointer transition-all hover:border-blue-400 hover:bg-blue-50 flex items-center justify-center"
                    onClick={() => {
                      // 添加新站点的逻辑，这里暂时用一个示例
                      const newSite: HospitalSite = {
                        id: `site_${Date.now()}`,
                        name: `医院站点 ${sites.length + 1}`,
                        center: [DEFAULT_CENTER[0] + Math.random() * 0.01, DEFAULT_CENTER[1] + Math.random() * 0.01],
                        zoom: DEFAULT_ZOOM,
                        address: '新增医院地址'
                      }
                      const newSites = [...sites, newSite]
                      setSites(newSites)
                      localStorage.setItem('hospital_sites', JSON.stringify(newSites))
                      handleSiteSelect(newSite.id)
                      toast.success(`已添加新站点: ${newSite.name}`)
                    }}
                  >
                    <div className="text-center">
                      <div className="w-8 h-8 bg-gray-300 rounded-full flex items-center justify-center mb-2 mx-auto">
                        <span className="text-gray-600 text-lg">+</span>
                      </div>
                      <p className="text-sm text-gray-600">添加站点</p>
                    </div>
                  </div>
                </div>
                
                {currentSite && (
                  <div className="mt-3 p-3 bg-white rounded border">
                    <p className="text-sm text-gray-700">
                      <span className="font-medium">当前站点:</span> {currentSite.name}
                      {currentSite.address && <span className="ml-2 text-gray-500">({currentSite.address})</span>}
                    </p>
                  </div>
                )}
              </div>
            </div>
            
            <div className={`flex ${isMobile ? 'flex-col' : 'flex-row'}`}>
              {/* 地图区域 */}
              <div className={`${isMobile ? 'w-full h-80' : 'flex-1'} relative bg-white rounded-lg border`}>
                {/* 地图显示模式控制 */}
                <div className={`absolute ${isMobile ? 'top-2 left-2' : 'top-4 left-4'} z-30 bg-white/90 backdrop-blur-sm rounded-lg border shadow-sm`}>
                  <div className={`flex flex-col p-${isMobile ? '1' : '2'} space-y-1`}>
                    <div className="text-xs font-medium text-gray-600 mb-1">
                      {isMobile ? '模式' : '显示模式'}
                    </div>
                    <div className={`flex ${isMobile ? 'flex-col' : 'flex-wrap'} gap-1`}>
                      <Button
                        size="sm"
                        variant={mapDisplayMode === 'overview' ? 'default' : 'outline'}
                        onClick={() => setMapDisplayMode('overview')}
                        className={`text-xs ${isMobile ? 'h-6 px-1' : 'h-7 px-2'}`}
                      >
                        {isMobile ? '🏥' : '🏥 概览'}
                      </Button>
                      <Button
                        size="sm"
                        variant={mapDisplayMode === 'departments' ? 'default' : 'outline'}
                        onClick={() => setMapDisplayMode('departments')}
                        className={`text-xs ${isMobile ? 'h-6 px-1' : 'h-7 px-2'}`}
                      >
                        {isMobile ? '🏥' : '🏥 科室'}
                      </Button>
                      <Button
                        size="sm"
                        variant={mapDisplayMode === 'equipment' ? 'default' : 'outline'}
                        onClick={() => setMapDisplayMode('equipment')}
                        className={`text-xs ${isMobile ? 'h-6 px-1' : 'h-7 px-2'}`}
                      >
                        {isMobile ? '🔬' : '🔬 设备'}
                      </Button>
                      <Button
                        size="sm"
                        variant={mapDisplayMode === 'alerts' ? 'default' : 'outline'}
                        onClick={() => setMapDisplayMode('alerts')}
                        className={`text-xs ${isMobile ? 'h-6 px-1' : 'h-7 px-2'}`}
                      >
                        {isMobile ? '⚠️' : '⚠️ 告警'}
                      </Button>
                    </div>
                  </div>
                </div>

                <OldHospitalMapViewer
                  ref={mapViewerRef}
                  amapKey={AMAP_KEY}
                  center={currentSite?.center || DEFAULT_CENTER}
                  zoom={currentSite?.zoom || DEFAULT_ZOOM}
                  svgModelUrl="/path/to/your/hospital.svg"
                  pois={pois}
                  emergencies={emergencies}
                  enableLocationMonitor={true}
                  apiBaseUrl={process.env.NEXT_PUBLIC_API_BASE_URL || 'https://api.zhihunyun.xyz'}
                  onMapClick={handleMapClick}
                  onUserLocationClick={(location) => {
                    console.log('用户位置点击:', location)
                    toast.info(`用户: ${location.username || location.userId}`, {
                      description: `部门: ${location.department || '访客'} | 精度: ${location.accuracy}m`
                    })
                  }}
                  onLocationRequestClick={(request) => {
                    console.log('位置请求点击:', request)
                    toast.info(`位置请求: ${request.title}`, {
                      description: `类型: ${request.type} | 优先级: ${request.priority}`
                    })
                  }}
                   onModelClick={(object: THREE.Object3D, point: THREE.Vector3) => {
                    setSelectedModel({ object, point })
                    setSelectedPosition(null)
                    if (object.name === 'floor') {
                      toast.success('点击地板 - 可添加设施点位')
                    } else {
                      toast.success(`点击建筑 - 可添加科室 (${object.name})`)
                    }
                  }}
                  onPOIClick={(poi: POIData) => {
                    toast.success(`选中POI: ${poi.name}`)
                  }}
                  onStoreClick={(store: StoreData) => {
                    toast.success(`选中商铺: ${store.name}`)
                  }}
                  onEmergencyClick={(emergency: EmergencyEvent) => {
                    setSelectedEmergency(emergency)
                    toast.info(`选中突发事件: ${emergency.title}`)
                  }}
                  className="w-full h-full rounded-lg"
                />

                {/* 快捷操作按钮 */}
                <div className={`absolute ${isMobile ? 'bottom-4 right-2' : 'top-4 right-4'} ${isMobile ? 'flex space-x-2' : 'space-y-2'} z-20`}>
                  <Button
                    onClick={() => {
                      console.log('🎯 点击添加POI按钮')
                      console.log('📍 当前状态:', { selectedPosition, selectedModel })
                      setShowAddPOI(true)
                    }}
                    disabled={!selectedPosition && !selectedModel}
                    variant="default"
                    size={isMobile ? "sm" : "sm"}
                    className={isMobile ? "text-xs px-2 py-1" : ""}
                    style={{
                      backgroundColor: (!selectedPosition && !selectedModel) ? '#ccc' : undefined,
                      opacity: (!selectedPosition && !selectedModel) ? 0.5 : 1
                    }}
                  >
                    {isMobile ? '+ POI' : '添加POI'}
                  </Button>
                  <Button
                    onClick={() => setShowAddStore(true)}
                    disabled={!selectedPosition && !selectedModel}
                    variant="secondary"
                    size={isMobile ? "sm" : "sm"}
                    className={isMobile ? "text-xs px-2 py-1" : ""}
                  >
                    {isMobile ? '+ 商铺' : '添加商铺'}
                  </Button>
                  <Button
                    onClick={() => {
                      const allPOIs = poiCatalog.getAllPOIs()
                      if (allPOIs.length === 0) {
                        toast.info('当前没有POI点位')
                        return
                      }
                      
                      const poiList = allPOIs.map(poi => `• ${poi.name} (${poi.id})`).join('\n')
                      const shareUrl = `${window.location.origin}/dashboard?poiIds=${allPOIs.map(p => p.id).join(',')}&zoom=16`
                      
                      navigator.clipboard.writeText(shareUrl).then(() => {
                        toast.success('所有POI分享链接已复制', {
                          description: `共${allPOIs.length}个POI:\n${poiList.slice(0, 100)}${poiList.length > 100 ? '...' : ''}`
                        })
                      })
                    }}
                    variant="ghost"
                    size={isMobile ? "sm" : "sm"}
                    className={isMobile ? "text-xs px-2 py-1" : ""}
                  >
                    {isMobile ? '📋' : '分享所有POI'}
                  </Button>
                  <Button
                    onClick={() => {
                      console.log('=== 地图状态检查 ===')
                      console.log('mapViewerRef.current:', mapViewerRef.current)
                      
                      if (mapViewerRef.current) {
                        const map = mapViewerRef.current.getMap()
                        console.log('内部地图实例:', map)
                        
                        if (map) {
                          console.log('地图中心:', map.getCenter())
                          console.log('地图缩放:', map.getZoom())
                          console.log('地图容器:', map.getContainer())
                        }
                        
                        const scene = mapViewerRef.current.getScene()
                        console.log('3D场景:', scene)
                        
                        const camera = mapViewerRef.current.getCamera()
                        console.log('摄像机:', camera)
                      }
                      
                      toast.info('地图状态已输出到控制台，请按F12查看')
                    }}
                    variant="outline"
                    size={isMobile ? "sm" : "sm"}
                    className={isMobile ? "text-xs px-2 py-1" : ""}
                  >
                    {isMobile ? '🔍' : '检查地图'}
                  </Button>
                  <Button
                    onClick={() => {
                      console.log('=== 当前状态检查 ===')
                      console.log('selectedPosition:', selectedPosition)
                      console.log('selectedModel:', selectedModel)
                      console.log('showAddPOI:', showAddPOI)
                      console.log('按钮应该', (!selectedPosition && !selectedModel) ? '禁用' : '启用')
                      toast.info(`位置: ${selectedPosition ? '已选中' : '未选中'}, 模型: ${selectedModel ? '已选中' : '未选中'}`)
                    }}
                    variant="outline"
                    size={isMobile ? "sm" : "sm"}
                    className={isMobile ? "text-xs px-2 py-1" : ""}
                  >
                    {isMobile ? '📊' : '状态检查'}
                  </Button>
                  <Button
                    onClick={() => {
                      console.log('🧪 手动触发位置设置测试...')
                      const testPosition: [number, number] = [115.1551, 30.2741]
                      setSelectedPosition(testPosition)
                      setSelectedModel(null)
                      toast.success(`手动设置位置: ${testPosition[0]}, ${testPosition[1]}`)
                    }}
                    variant="secondary"
                    size={isMobile ? "sm" : "sm"}
                    className={isMobile ? "text-xs px-2 py-1" : ""}
                  >
                    {isMobile ? '🧪' : '手动测试'}
                  </Button>
                </div>

                {/* 选中位置信息 */}
                {(selectedPosition || selectedModel) && (
                  <div className="absolute bottom-4 left-4 bg-white/90 rounded-lg p-3 text-sm z-20 shadow-lg">
                    {selectedPosition && (
                      <div>
                        <p className="font-medium">地图位置:</p>
                        <p>经度: {selectedPosition[0].toFixed(6)}</p>
                        <p>纬度: {selectedPosition[1].toFixed(6)}</p>
                      </div>
                    )}
                    {selectedModel && (
                      <div>
                        <p className="font-medium">模型对象:</p>
                        <p>名称: {selectedModel.object.name}</p>
                        <p>坐标: {selectedModel.point.x.toFixed(2)}, {selectedModel.point.y.toFixed(2)}, {selectedModel.point.z.toFixed(2)}</p>
                      </div>
                    )}
                  </div>
                )}
              </div>

              {/* 医院地图管理侧边栏 */}
              <div className={`${isMobile ? 'w-full mt-4' : 'w-80 ml-4'} bg-white ${isMobile ? 'border-t' : 'border-l'} rounded-lg flex flex-col ${isMobile ? 'h-96' : ''}`}>
                <Tabs defaultValue="sites" className="flex flex-col h-full">
                  <div className={`${isMobile ? 'p-2' : 'p-4'} border-b`}>
                    <TabsList className={`grid grid-cols-4 ${isMobile ? 'text-xs h-8' : 'text-xs'}`}>
                      <TabsTrigger value="sites" className={isMobile ? 'px-1' : ''}>
                        {isMobile ? '🏥' : '医院'}
                      </TabsTrigger>
                      <TabsTrigger value="emergency" className={isMobile ? 'px-1' : ''}>
                        {isMobile ? '🚨' : '事件'}
                      </TabsTrigger>
                      <TabsTrigger value="poi" className={isMobile ? 'px-1' : ''}>
                        {isMobile ? '📍' : 'POI'}
                      </TabsTrigger>
                      <TabsTrigger value="data" className={isMobile ? 'px-1' : ''}>
                        {isMobile ? '📊' : '数据'}
                      </TabsTrigger>
                    </TabsList>
                  </div>
                  
                  {/* 医院站点管理 */}
                  <TabsContent value="sites" className="flex-1 overflow-auto">
                    <div className={`${isMobile ? 'p-2' : 'p-4'} space-y-${isMobile ? '2' : '4'}`}>
                      <div className="flex items-center justify-between">
                        <h3 className="font-medium text-sm">医院站点选择</h3>
                        <Badge variant="secondary" className="text-xs">
                          {sites.length} 个站点
                        </Badge>
                      </div>
                      
                      {/* 当前选中的医院 */}
                      {currentSite && (
                        <Card className="border-blue-200 bg-blue-50">
                          <CardHeader className="pb-2">
                            <CardTitle className="text-sm flex items-center">
                              🏥 {currentSite.name}
                              <Badge variant="default" className="ml-2 text-xs">当前</Badge>
                            </CardTitle>
                          </CardHeader>
                          <CardContent className="text-xs text-gray-600">
                            <p>坐标: {currentSite.center[0].toFixed(4)}, {currentSite.center[1].toFixed(4)}</p>
                            {currentSite.address && <p className="mt-1">地址: {currentSite.address}</p>}
                            <div className="flex gap-1 mt-2">
                              <Button 
                                size="sm" 
                                variant="outline" 
                                className="text-xs h-6 px-2"
                                onClick={() => {
                                  if (mapViewerRef.current) {
                                    mapViewerRef.current.flyTo(currentSite.center, currentSite.zoom || DEFAULT_ZOOM)
                                  }
                                  toast.success('已定位到医院')
                                }}
                              >
                                📍 定位
                              </Button>
                              <Button 
                                size="sm" 
                                variant="outline" 
                                className="text-xs h-6 px-2"
                                onClick={() => {
                                  setMapDisplayMode('departments')
                                  setTimeout(() => {
                                    const data = realDataService.getAllRealTimeData()
                                    updateMapData(data)
                                  }, 100)
                                  toast.success('已切换到科室视图')
                                }}
                              >
                                🏥 科室
                              </Button>
                            </div>
                          </CardContent>
                        </Card>
                      )}
                      
                      {/* 其他医院列表 */}
                      <div className="space-y-2">
                        <div className="text-xs font-medium text-gray-600">切换医院站点</div>
                        {sites.filter(site => site.id !== currentSiteId).map((site) => (
                          <Card 
                            key={site.id}
                            className="cursor-pointer hover:shadow-sm transition-all hover:border-blue-200"
                            onClick={() => handleSiteSelect(site.id)}
                          >
                            <CardContent className="p-3">
                              <div className="flex items-center justify-between">
                                <div className="flex-1">
                                  <div className="font-medium text-sm">{site.name}</div>
                                  <div className="text-xs text-gray-500 mt-1">
                                    {site.address || `${site.center[0].toFixed(4)}, ${site.center[1].toFixed(4)}`}
                                  </div>
                                </div>
                                <Button size="sm" variant="ghost" className="text-xs h-6 px-2">
                                  切换
                                </Button>
                              </div>
                            </CardContent>
                          </Card>
                        ))}
                      </div>
                      
                      {/* 显示模式快速切换 */}
                      <Card>
                        <CardHeader className="pb-2">
                          <CardTitle className="text-sm">地图显示模式</CardTitle>
                          <CardDescription className="text-xs">
                            当前: {mapDisplayMode === 'overview' ? '概览模式' : 
                                   mapDisplayMode === 'departments' ? '科室模式' :
                                   mapDisplayMode === 'equipment' ? '设备模式' : '告警模式'}
                          </CardDescription>
                        </CardHeader>
                        <CardContent>
                          <div className="grid grid-cols-2 gap-2">
                            <Button
                              size="sm"
                              variant={mapDisplayMode === 'overview' ? 'default' : 'outline'}
                              onClick={() => setMapDisplayMode('overview')}
                              className="text-xs"
                            >
                              🏥 概览
                            </Button>
                            <Button
                              size="sm"
                              variant={mapDisplayMode === 'departments' ? 'default' : 'outline'}
                              onClick={() => setMapDisplayMode('departments')}
                              className="text-xs"
                            >
                              🏥 科室
                            </Button>
                            <Button
                              size="sm"
                              variant={mapDisplayMode === 'equipment' ? 'default' : 'outline'}
                              onClick={() => setMapDisplayMode('equipment')}
                              className="text-xs"
                            >
                              🔬 设备
                            </Button>
                            <Button
                              size="sm"
                              variant={mapDisplayMode === 'alerts' ? 'default' : 'outline'}
                              onClick={() => setMapDisplayMode('alerts')}
                              className="text-xs"
                            >
                              ⚠️ 告警
                            </Button>
                          </div>
                        </CardContent>
                      </Card>
                    </div>
                  </TabsContent>
                  
                  {/* 突发事件管理 */}
                  <TabsContent value="emergency" className="flex-1 overflow-hidden">
                    <EmergencyPanel 
                      onEmergencySelect={handleEmergencySelect}
                      onEmergencyCreate={handleEmergencyCreate}
                      className="h-full"
                    />
                  </TabsContent>
                  
                  {/* POI管理 */}
                  <TabsContent value="poi" className="flex-1 overflow-auto">
                    <div className={`${isMobile ? 'p-2' : 'p-4'} space-y-${isMobile ? '2' : '4'}`}>
                      {/* POI统计概览 */}
                      <Card>
                        <CardHeader className="pb-2">
                          <CardTitle className="text-sm">POI统计</CardTitle>
                          <CardDescription className="text-xs">当前地图上的点位信息</CardDescription>
                        </CardHeader>
                        <CardContent>
                          <div className="grid grid-cols-2 gap-2 text-xs">
                            <div className="text-center p-2 bg-blue-50 rounded">
                              <div className="font-medium text-lg">{pois.filter(p => p.type === 'department').length}</div>
                              <div className="text-gray-600">科室</div>
                            </div>
                            <div className="text-center p-2 bg-green-50 rounded">
                              <div className="font-medium text-lg">{pois.filter(p => p.type === 'equipment').length}</div>
                              <div className="text-gray-600">设备</div>
                            </div>
                            <div className="text-center p-2 bg-orange-50 rounded">
                              <div className="font-medium text-lg">{pois.filter(p => p.type === 'entrance').length}</div>
                              <div className="text-gray-600">入口</div>
                            </div>
                            <div className="text-center p-2 bg-red-50 rounded">
                              <div className="font-medium text-lg">{pois.filter(p => p.type === 'emergency').length}</div>
                              <div className="text-gray-600">紧急</div>
                            </div>
                          </div>
                        </CardContent>
                      </Card>
                      
                      {/* POI列表 */}
                      <Card>
                        <CardHeader className="pb-2">
                          <CardTitle className="text-sm">POI点位列表 ({pois.length})</CardTitle>
                          <CardDescription className="text-xs">点击任意POI可在地图上定位</CardDescription>
                        </CardHeader>
                        <CardContent>
                          <div className="space-y-2 max-h-64 overflow-y-auto">
                            {pois.map((poi) => (
                              <div
                                key={poi.id}
                                className="p-2 border rounded cursor-pointer hover:bg-gray-50 transition-colors"
                                onClick={() => {
                                  if (mapViewerRef.current) {
                                    mapViewerRef.current.flyTo(poi.position, 18)
                                  }
                                  toast.success(`定位到: ${poi.name}`)
                                }}
                              >
                                <div className="flex items-center justify-between">
                                  <div className="flex-1">
                                    <div className="font-medium text-sm">{poi.name}</div>
                                    <div className="text-xs text-gray-500">
                                      {poi.type === 'department' ? '🏥' : 
                                       poi.type === 'equipment' ? '🔬' : 
                                       poi.type === 'entrance' ? '🚪' : '⚠️'} 
                                      {poi.type} • {poi.floor}
                                    </div>
                                  </div>
                                  <Button size="sm" variant="ghost" className="text-xs h-6 px-2">
                                    📍
                                  </Button>
                                </div>
                              </div>
                            ))}
                            {pois.length === 0 && (
                              <div className="text-center text-gray-500 py-8">
                                <p className="text-sm">暂无POI数据</p>
                                <p className="text-xs mt-1">切换显示模式或添加POI点位</p>
                                <Button 
                                  size="sm" 
                                  className="mt-2 text-xs"
                                  onClick={() => setMapDisplayMode('departments')}
                                >
                                  显示科室
                                </Button>
                              </div>
                            )}
                          </div>
                        </CardContent>
                      </Card>

                      {/* 商铺列表 */}
                      <Card>
                        <CardHeader className="pb-2">
                          <CardTitle className="text-sm">商铺信息 ({stores.length})</CardTitle>
                          <CardDescription className="text-xs">医院内商业设施</CardDescription>
                        </CardHeader>
                        <CardContent>
                          <div className="space-y-2 max-h-32 overflow-y-auto">
                            {stores.map((store) => (
                              <div
                                key={store.id}
                                className="p-2 border rounded cursor-pointer hover:bg-gray-50"
                                onClick={() => {
                                  if (mapViewerRef.current) {
                                    mapViewerRef.current.flyTo(store.lnglat, 18)
                                  }
                                  toast.success(`定位到: ${store.name}`)
                                }}
                              >
                                <div className="font-medium text-sm">{store.name}</div>
                                <div className="text-xs text-gray-500">🏪 {store.business}</div>
                              </div>
                            ))}
                            {stores.length === 0 && (
                              <div className="text-center text-gray-500 py-4">
                                <p className="text-xs">暂无商铺数据</p>
                              </div>
                            )}
                          </div>
                        </CardContent>
                      </Card>
                    </div>
                  </TabsContent>
                  
                  {/* 数据面板 */}
                  <TabsContent value="data" className="flex-1 overflow-auto">
                    <div className={`${isMobile ? 'p-2' : 'p-4'} space-y-${isMobile ? '2' : '4'}`}>
                      {/* 实时数据概览 */}
                      <Card>
                        <CardHeader className="pb-2">
                          <CardTitle className="text-sm">实时数据概览</CardTitle>
                          <CardDescription className="text-xs">医院系统数据统计</CardDescription>
                        </CardHeader>
                        <CardContent>
                          <div className="space-y-3 text-xs">
                            <div className="flex justify-between">
                              <span>科室总数</span>
                              <span className="font-medium">{realDataService.getAllRealTimeData().departments?.length || 0}</span>
                            </div>
                            <div className="flex justify-between">
                              <span>设备总数</span>
                              <span className="font-medium">{realDataService.getAllRealTimeData().equipment?.length || 0}</span>
                            </div>
                            <div className="flex justify-between">
                              <span>活跃告警</span>
                              <span className="font-medium text-red-600">
                                {realDataService.getAllRealTimeData().alerts?.filter((a: Alert) => a.status === 'active').length || 0}
                              </span>
                            </div>
                            <div className="flex justify-between">
                              <span>当前POI</span>
                              <span className="font-medium">{pois.length}</span>
                            </div>
                            <div className="flex justify-between">
                              <span>显示模式</span>
                              <span className="font-medium text-blue-600">
                                {mapDisplayMode === 'overview' ? '概览' : 
                                 mapDisplayMode === 'departments' ? '科室' :
                                 mapDisplayMode === 'equipment' ? '设备' : '告警'}
                              </span>
                            </div>
                          </div>
                        </CardContent>
                      </Card>
                      
                      {/* 操作控制 */}
                      <Card>
                        <CardHeader className="pb-2">
                          <CardTitle className="text-sm">地图控制</CardTitle>
                          <CardDescription className="text-xs">地图数据和视角控制</CardDescription>
                        </CardHeader>
                        <CardContent>
                          <div className="space-y-2">
                            <Button 
                              size="sm" 
                              className="w-full text-xs"
                              onClick={() => {
                                const data = realDataService.getAllRealTimeData()
                                updateMapData(data)
                                toast.success('地图数据已刷新')
                              }}
                            >
                              🔄 刷新地图数据
                            </Button>
                            <Button 
                              size="sm" 
                              variant="outline" 
                              className="w-full text-xs"
                              onClick={() => {
                                if (mapViewerRef.current) {
                                  mapViewerRef.current.clearHighlight()
                                }
                                setSelectedPosition(null)
                                setSelectedModel(null)
                                toast.success('已清除选择状态')
                              }}
                            >
                              🧹 清除选择
                            </Button>
                            <Button 
                              size="sm" 
                              variant="outline" 
                              className="w-full text-xs"
                              onClick={() => {
                                if (currentSite && mapViewerRef.current) {
                                  mapViewerRef.current.flyTo(currentSite.center, currentSite.zoom || DEFAULT_ZOOM)
                                  toast.success('已重置视角')
                                }
                              }}
                            >
                              🎯 重置视角
                            </Button>
                            <Button 
                              size="sm" 
                              variant="outline" 
                              className="w-full text-xs"
                              onClick={() => router.push('/hospital-management')}
                            >
                              ⚙️ 医院管理
                            </Button>
                          </div>
                        </CardContent>
                      </Card>
                    </div>
                  </TabsContent>
                </Tabs>
              </div>
            </div>
          </div>
        )

      case 'patients':
        return (
          <div className="h-full">
            <div className="mb-4">
              <h2 className="text-2xl font-bold text-gray-900 mb-2">患者管理</h2>
              <p className="text-gray-600">患者信息管理、就诊记录、预约挂号统计</p>
            </div>

            {/* 患者统计卡片 */}
            <div className="grid grid-cols-1 md:grid-cols-4 gap-6 mb-6">
              <Card>
                <CardContent className="p-6">
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="text-gray-600 text-sm">今日门诊</p>
                      <p className="text-2xl font-bold text-blue-600">
                        {patientStatsLoading ? '...' : patientStats.todayAppointments.count}
                      </p>
                      <p className={`text-xs ${patientStats.todayAppointments.change >= 0 ? 'text-green-600' : 'text-red-600'}`}>
                        {patientStats.todayAppointments.change >= 0 ? '↗' : '↘'} {Math.abs(patientStats.todayAppointments.change).toFixed(1)}%
                      </p>
                    </div>
                    <IconUsers className="w-8 h-8 text-blue-500" />
                  </div>
                </CardContent>
              </Card>

              <Card>
                <CardContent className="p-6">
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="text-gray-600 text-sm">住院患者</p>
                      <p className="text-2xl font-bold text-green-600">
                        {patientStatsLoading ? '...' : patientStats.inPatients.count}
                      </p>
                      <p className={`text-xs ${patientStats.inPatients.change >= 0 ? 'text-green-600' : 'text-red-600'}`}>
                        {patientStats.inPatients.change >= 0 ? '↗' : '↘'} {Math.abs(patientStats.inPatients.change).toFixed(1)}%
                      </p>
                    </div>
                    <IconBed className="w-8 h-8 text-green-500" />
                  </div>
                </CardContent>
              </Card>

              <Card 
                className="cursor-pointer hover:shadow-lg transition-all duration-200 hover:scale-105"
                onClick={() => setSelectedMenu('appointment-management')}
              >
                <CardContent className="p-6">
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="text-gray-600 text-sm">预约挂号</p>
                      <p className="text-2xl font-bold text-purple-600">
                        {patientStatsLoading ? '...' : patientStats.todayBookings.count}
                      </p>
                      <p className={`text-xs ${patientStats.todayBookings.change >= 0 ? 'text-green-600' : 'text-red-600'}`}>
                        {patientStats.todayBookings.change >= 0 ? '↗' : '↘'} {Math.abs(patientStats.todayBookings.change).toFixed(1)}%
                      </p>
                      <p className="text-xs text-blue-600 mt-1">点击查看详情 →</p>
                    </div>
                    <IconCalendar className="w-8 h-8 text-purple-500" />
                  </div>
                </CardContent>
              </Card>

              <Card>
                <CardContent className="p-6">
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="text-gray-600 text-sm">急诊患者</p>
                      <p className="text-2xl font-bold text-red-600">
                        {patientStatsLoading ? '...' : patientStats.emergencyPatients.count}
                      </p>
                      <p className={`text-xs ${patientStats.emergencyPatients.change >= 0 ? 'text-orange-600' : 'text-green-600'}`}>
                        {patientStats.emergencyPatients.change >= 0 ? '↗' : '↘'} {Math.abs(patientStats.emergencyPatients.change).toFixed(1)}%
                      </p>
                    </div>
                    <IconAlertTriangle className="w-8 h-8 text-red-500" />
                  </div>
                </CardContent>
              </Card>
            </div>

            {/* 患者列表 */}
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
              <Card>
                <CardHeader>
                  <CardTitle className="flex items-center gap-2">
                    <IconUsers className="w-5 h-5" />
                    今日门诊患者
                  </CardTitle>
                  <CardDescription>最近就诊的门诊患者</CardDescription>
                </CardHeader>
                <CardContent className="max-h-96 overflow-y-auto">
                  {patientStatsLoading ? (
                    <div className="flex items-center justify-center py-8">
                      <div className="text-gray-500">加载中...</div>
                    </div>
                  ) : todayPatients.length === 0 ? (
                    <div className="flex items-center justify-center py-8">
                      <div className="text-gray-500">暂无今日门诊患者</div>
                    </div>
                  ) : (
                    <div className="space-y-3">
                      {todayPatients.map((patient, index) => (
                      <div key={index} className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                        <div className="flex items-center space-x-3">
                          <div className="w-10 h-10 bg-blue-100 rounded-full flex items-center justify-center">
                            <span className="text-blue-600 font-medium text-sm">{patient.name.charAt(0)}</span>
                          </div>
                          <div>
                            <p className="font-medium">{patient.name}</p>
                            <p className="text-sm text-gray-600">{patient.age}岁 | {patient.department}</p>
                          </div>
                        </div>
                        <div className="text-right">
                          <p className="text-sm font-medium">{patient.time}</p>
                          <Badge variant={
                            patient.status === '就诊中' ? 'default' : 
                            patient.status === '等待中' ? 'secondary' : 
                            patient.status === '已完成' ? 'outline' : 'destructive'
                          } className="text-xs">
                            {patient.status}
                          </Badge>
                        </div>
                      </div>
                      ))}
                    </div>
                  )}
                </CardContent>
              </Card>

              <Card>
                <CardHeader>
                  <CardTitle className="flex items-center gap-2">
                    <IconBed className="w-5 h-5" />
                    住院患者概览
                  </CardTitle>
                  <CardDescription>住院部患者分布情况</CardDescription>
                </CardHeader>
                <CardContent>
                  {patientStatsLoading ? (
                    <div className="flex items-center justify-center py-8">
                      <div className="text-gray-500">加载中...</div>
                    </div>
                  ) : inpatientOverview.length === 0 ? (
                    <div className="flex items-center justify-center py-8">
                      <div className="text-gray-500">暂无住院患者数据</div>
                    </div>
                  ) : (
                    <div className="space-y-4">
                      {inpatientOverview.map((dept, index) => (
                      <div key={index} className="p-3 border rounded-lg">
                        <div className="flex items-center justify-between mb-2">
                          <span className="font-medium">{dept.department}</span>
                          <span className="text-sm text-gray-600">{dept.patients}/{dept.beds} 床位</span>
                        </div>
                        <div className="flex items-center space-x-2">
                          <Progress value={dept.utilizationRate} className="flex-1" />
                          <span className="text-sm font-medium text-gray-600">{dept.utilizationRate}%</span>
                        </div>
                      </div>
                      ))}
                    </div>
                  )}
                </CardContent>
              </Card>
            </div>
          </div>
        )

      case 'departments':
        return (
          <div className="h-full">
            <div className="mb-4">
              <h2 className="text-2xl font-bold text-gray-900 mb-2">科室管理</h2>
              <p className="text-gray-600">医院科室信息管理、人员配置、资源分配</p>
            </div>

            {/* 科室概览卡片 */}
            <div className="grid grid-cols-1 md:grid-cols-4 gap-6 mb-6">
              <Card>
                <CardContent className="p-6">
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="text-gray-600 text-sm">科室总数</p>
                      <p className="text-2xl font-bold text-blue-600">{hospitalData.departments.length}</p>
                      <p className="text-xs text-gray-500">个科室</p>
                    </div>
                    <IconFolder className="w-8 h-8 text-blue-500" />
                  </div>
                </CardContent>
              </Card>

              <Card>
                <CardContent className="p-6">
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="text-gray-600 text-sm">在职医生</p>
                      <p className="text-2xl font-bold text-green-600">156</p>
                      <p className="text-xs text-green-600">↗ +8人</p>
                    </div>
                    <IconUsers className="w-8 h-8 text-green-500" />
                  </div>
                </CardContent>
              </Card>

              <Card>
                <CardContent className="p-6">
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="text-gray-600 text-sm">护理人员</p>
                      <p className="text-2xl font-bold text-purple-600">284</p>
                      <p className="text-xs text-purple-600">↗ +12人</p>
                    </div>
                    <IconActivity className="w-8 h-8 text-purple-500" />
                  </div>
                </CardContent>
              </Card>

              <Card>
                <CardContent className="p-6">
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="text-gray-600 text-sm">科室负载</p>
                      <p className="text-2xl font-bold text-orange-600">78%</p>
                      <p className="text-xs text-orange-600">平均负载率</p>
                    </div>
                    <IconChartBar className="w-8 h-8 text-orange-500" />
                  </div>
                </CardContent>
              </Card>
            </div>

            {/* 科室列表 */}
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <IconFolder className="w-5 h-5" />
                  科室详细信息
                </CardTitle>
                <CardDescription>各科室基本信息和运营状态</CardDescription>
              </CardHeader>
              <CardContent>
                <div className="grid grid-cols-1 lg:grid-cols-2 xl:grid-cols-3 gap-6">
                  {hospitalData.departments.slice(0, 12).map((dept, index) => (
                    <div key={dept.id} className="p-4 border rounded-lg hover:shadow-md transition-shadow">
                      <div className="flex items-center justify-between mb-3">
                        <h3 className="font-medium text-gray-900">{dept.name}</h3>
                        <Badge variant={dept.status === 'active' ? 'default' : 'secondary'}>
                          {dept.status === 'active' ? '运行中' : '维护中'}
                        </Badge>
                      </div>
                      
                      <div className="space-y-2 text-sm text-gray-600">
                        <div className="flex justify-between">
                          <span>科室类型:</span>
                          <span className="font-medium">{dept.type === 'emergency' ? '急诊科' : 
                                dept.type === 'outpatient' ? '门诊科' : 
                                dept.type === 'surgery' ? '手术科' : 
                                dept.type === 'inpatient' ? '住院科' : '专科'}</span>
                        </div>
                        <div className="flex justify-between">
                          <span>床位容量:</span>
                          <span className="font-medium">{dept.capacity || Math.floor(Math.random() * 50) + 10} 个</span>
                        </div>
                        <div className="flex justify-between">
                          <span>医护人员:</span>
                          <span className="font-medium">{Math.floor(Math.random() * 20) + 8} 人</span>
                        </div>
                        <div className="flex justify-between">
                          <span>今日接诊:</span>
                          <span className="font-medium text-blue-600">{Math.floor(Math.random() * 80) + 20} 人次</span>
                        </div>
                      </div>

                      <div className="mt-3 pt-3 border-t">
                        <div className="flex justify-between text-xs text-gray-500 mb-1">
                          <span>负载率</span>
                          <span>{Math.floor(Math.random() * 40) + 60}%</span>
                        </div>
                        <Progress value={Math.floor(Math.random() * 40) + 60} className="h-1.5" />
                      </div>
                    </div>
                  ))}
                </div>

                {hospitalData.departments.length > 12 && (
                  <div className="mt-6 text-center">
                    <Button variant="outline">
                      查看全部 {hospitalData.departments.length} 个科室
                    </Button>
                  </div>
                )}
              </CardContent>
            </Card>
          </div>
        )

      case 'system':
        return (
          <div className="h-full">
            <div className="mb-4">
              <h2 className="text-2xl font-bold text-gray-900 mb-2">系统状态</h2>
              <p className="text-gray-600">医院信息系统运行状态监控</p>
            </div>

            {/* 系统状态概览 */}
            <div className="grid grid-cols-1 md:grid-cols-4 gap-6 mb-6">
              <Card>
                <CardContent className="p-6">
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="text-gray-600 text-sm">系统状态</p>
                      <p className="text-lg font-bold text-green-600">正常运行</p>
                      <p className="text-xs text-green-600">99.9% 可用性</p>
                    </div>
                    <div className="w-3 h-3 bg-green-500 rounded-full animate-pulse"></div>
                  </div>
                </CardContent>
              </Card>

              <Card>
                <CardContent className="p-6">
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="text-gray-600 text-sm">在线用户</p>
                      <p className="text-2xl font-bold text-blue-600">342</p>
                      <p className="text-xs text-blue-600">医护人员</p>
                    </div>
                    <IconUsers className="w-8 h-8 text-blue-500" />
                  </div>
                </CardContent>
              </Card>

              <Card>
                <CardContent className="p-6">
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="text-gray-600 text-sm">数据库</p>
                      <p className="text-lg font-bold text-green-600">健康</p>
                      <p className="text-xs text-gray-500">23.4GB 使用</p>
                    </div>
                    <IconActivity className="w-8 h-8 text-green-500" />
                  </div>
                </CardContent>
              </Card>

              <Card>
                <CardContent className="p-6">
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="text-gray-600 text-sm">服务器负载</p>
                      <p className="text-2xl font-bold text-orange-600">68%</p>
                      <p className="text-xs text-orange-600">CPU使用率</p>
                    </div>
                    <IconChartBar className="w-8 h-8 text-orange-500" />
                  </div>
                </CardContent>
              </Card>
            </div>

            {/* 系统模块状态 */}
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
              <Card>
                <CardHeader>
                  <CardTitle>核心系统模块</CardTitle>
                  <CardDescription>主要业务系统运行状态</CardDescription>
                </CardHeader>
                <CardContent className="space-y-3">
                  {[
                    { name: 'HIS 医院信息系统', status: 'online', uptime: '99.9%' },
                    { name: 'EMR 电子病历系统', status: 'online', uptime: '99.7%' },
                    { name: 'PACS 影像系统', status: 'online', uptime: '99.8%' },
                    { name: 'LIS 实验室系统', status: 'maintenance', uptime: '98.5%' },
                    { name: '药房管理系统', status: 'online', uptime: '99.6%' },
                    { name: '护理管理系统', status: 'online', uptime: '99.4%' }
                  ].map((system, index) => (
                    <div key={index} className="flex items-center justify-between p-3 border rounded-lg">
                      <div className="flex items-center space-x-3">
                        <div className={`w-3 h-3 rounded-full ${
                          system.status === 'online' ? 'bg-green-500' : 
                          system.status === 'maintenance' ? 'bg-yellow-500' : 'bg-red-500'
                        }`}></div>
                        <span className="font-medium">{system.name}</span>
                      </div>
                      <div className="text-right">
                        <div className="text-sm font-medium">{system.uptime}</div>
                        <div className="text-xs text-gray-500">
                          {system.status === 'online' ? '运行中' : 
                           system.status === 'maintenance' ? '维护中' : '故障'}
                        </div>
                      </div>
                    </div>
                  ))}
                </CardContent>
              </Card>

              <Card>
                <CardHeader>
                  <CardTitle>系统资源使用</CardTitle>
                  <CardDescription>服务器资源实时监控</CardDescription>
                </CardHeader>
                <CardContent className="space-y-4">
                  <div>
                    <div className="flex justify-between text-sm mb-2">
                      <span>CPU使用率</span>
                      <span>68%</span>
                    </div>
                    <Progress value={68} className="h-2" />
                  </div>
                  <div>
                    <div className="flex justify-between text-sm mb-2">
                      <span>内存使用率</span>
                      <span>54%</span>
                    </div>
                    <Progress value={54} className="h-2" />
                  </div>
                  <div>
                    <div className="flex justify-between text-sm mb-2">
                      <span>磁盘使用率</span>
                      <span>32%</span>
                    </div>
                    <Progress value={32} className="h-2" />
                  </div>
                  <div>
                    <div className="flex justify-between text-sm mb-2">
                      <span>网络带宽</span>
                      <span>23%</span>
                    </div>
                    <Progress value={23} className="h-2" />
                  </div>

                  <div className="mt-6 p-3 bg-green-50 border border-green-200 rounded-lg">
                    <div className="text-sm text-green-800 font-medium mb-1">系统运行正常</div>
                    <div className="text-xs text-green-600">
                      所有核心模块运行稳定，资源使用率在正常范围内
                    </div>
                  </div>
                </CardContent>
              </Card>
            </div>
          </div>
        )

      case 'devices':
        return (
          <div className="h-full">
            <div className="mb-4">
              <h2 className="text-2xl font-bold text-gray-900 mb-2">设备管理</h2>
              <p className="text-gray-600">医疗设备状态监控、维护计划、使用统计</p>
            </div>

            {/* 设备统计卡片 */}
            <div className="grid grid-cols-1 md:grid-cols-4 gap-6 mb-6">
              <Card>
                <CardContent className="p-6">
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="text-gray-600 text-sm">设备总数</p>
                      <p className="text-2xl font-bold text-blue-600">{hospitalData.equipment.length}</p>
                      <p className="text-xs text-gray-500">台设备</p>
                    </div>
                    <IconBed className="w-8 h-8 text-blue-500" />
                  </div>
                </CardContent>
              </Card>

              <Card>
                <CardContent className="p-6">
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="text-gray-600 text-sm">正常运行</p>
                      <p className="text-2xl font-bold text-green-600">{hospitalData.equipment.filter(e => e.status === 'active').length}</p>
                      <p className="text-xs text-green-600">设备正常</p>
                    </div>
                    <div className="w-8 h-8 bg-green-100 rounded-full flex items-center justify-center">
                      <div className="w-3 h-3 bg-green-500 rounded-full"></div>
                    </div>
                  </div>
                </CardContent>
              </Card>

              <Card>
                <CardContent className="p-6">
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="text-gray-600 text-sm">维护中</p>
                      <p className="text-2xl font-bold text-yellow-600">{hospitalData.equipment.filter(e => e.status === 'maintenance').length}</p>
                      <p className="text-xs text-yellow-600">需要维护</p>
                    </div>
                    <div className="w-8 h-8 bg-yellow-100 rounded-full flex items-center justify-center">
                      <div className="w-3 h-3 bg-yellow-500 rounded-full"></div>
                    </div>
                  </div>
                </CardContent>
              </Card>

              <Card>
                <CardContent className="p-6">
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="text-gray-600 text-sm">故障设备</p>
                      <p className="text-2xl font-bold text-red-600">{hospitalData.equipment.filter(e => e.status === 'error').length}</p>
                      <p className="text-xs text-red-600">需要维修</p>
                    </div>
                    <IconAlertTriangle className="w-8 h-8 text-red-500" />
                  </div>
                </CardContent>
              </Card>
            </div>

            {/* 设备分类统计 */}
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
              <Card>
                <CardHeader>
                  <CardTitle>设备分类统计</CardTitle>
                  <CardDescription>按设备类型分组的统计信息</CardDescription>
                </CardHeader>
                <CardContent>
                  <div className="space-y-4">
                    {['监护设备', '检验设备', '影像设备', '治疗设备', '手术设备'].map((type, index) => {
                      const count = hospitalData.equipment.filter(e => e.type === type).length
                      const percentage = Math.round((count / hospitalData.equipment.length) * 100)
                      return (
                        <div key={type} className="flex items-center justify-between">
                          <span className="font-medium">{type}</span>
                          <div className="flex items-center space-x-2">
                            <div className="w-20 h-2 bg-gray-200 rounded-full">
                              <div 
                                className="h-full bg-blue-500 rounded-full" 
                                style={{ width: `${percentage}%` }}
                              ></div>
                            </div>
                            <span className="text-sm text-gray-600 min-w-[3rem] text-right">{count} 台</span>
                          </div>
                        </div>
                      )
                    })}
                  </div>
                </CardContent>
              </Card>

              <Card>
                <CardHeader>
                  <CardTitle>近期维护计划</CardTitle>
                  <CardDescription>设备维护和检修安排</CardDescription>
                </CardHeader>
                <CardContent>
                  <div className="space-y-3">
                    {[
                      { name: 'MRI-001', type: 'MRI设备', date: '2023-12-20', status: '计划中' },
                      { name: 'CT-003', type: 'CT扫描仪', date: '2023-12-22', status: '进行中' },
                      { name: 'X-RAY-005', type: 'X光机', date: '2023-12-25', status: '计划中' },
                      { name: 'ECHO-002', type: '超声设备', date: '2023-12-28', status: '计划中' },
                      { name: 'MONITOR-012', type: '监护设备', date: '2023-12-30', status: '已延期' }
                    ].map((maintenance, index) => (
                      <div key={index} className="flex items-center justify-between p-3 border rounded-lg">
                        <div>
                          <p className="font-medium">{maintenance.name}</p>
                          <p className="text-sm text-gray-600">{maintenance.type}</p>
                        </div>
                        <div className="text-right">
                          <p className="text-sm">{maintenance.date}</p>
                          <Badge variant={
                            maintenance.status === '进行中' ? 'default' : 
                            maintenance.status === '已延期' ? 'destructive' : 'secondary'
                          }>
                            {maintenance.status}
                          </Badge>
                        </div>
                      </div>
                    ))}
                  </div>
                </CardContent>
              </Card>
            </div>
          </div>
        )

      case 'ai-control':
        return (
          <div className="h-full">
            <div className="mb-4">
              <h2 className="text-2xl font-bold text-gray-900 mb-2">AI智能控制台</h2>
              <p className="text-gray-600">预测分析、智能监控、AI助手统一管理</p>
            </div>
            {/* 这里集成AIDashboard组件 */}
            <div className="bg-white rounded-lg shadow-sm">
              <div className="p-6">
                {/* 快速功能卡片 */}
                <div className="grid grid-cols-1 md:grid-cols-3 gap-6 mb-6">
                  <div className="bg-gradient-to-r from-blue-50 to-blue-100 p-4 rounded-lg border border-blue-200">
                    <div className="flex items-center justify-between">
                      <div>
                        <h3 className="font-semibold text-blue-900 mb-1">AI对话助手</h3>
                        <p className="text-blue-700 text-sm">智能问答、语音交互</p>
                      </div>
                      <IconChartBar className="w-8 h-8 text-blue-600" />
                    </div>
                    <div className="mt-3">
                      <div className="text-2xl font-bold text-blue-900">456</div>
                      <div className="text-blue-600 text-sm">次对话</div>
                    </div>
                  </div>

                  <div className="bg-gradient-to-r from-green-50 to-green-100 p-4 rounded-lg border border-green-200">
                    <div className="flex items-center justify-between">
                      <div>
                        <h3 className="font-semibold text-green-900 mb-1">预测分析</h3>
                        <p className="text-green-700 text-sm">流量预测、故障预警</p>
                      </div>
                      <IconTrendingUp className="w-8 h-8 text-green-600" />
                    </div>
                    <div className="mt-3">
                      <div className="text-2xl font-bold text-green-900">28</div>
                      <div className="text-green-600 text-sm">个预测</div>
                    </div>
                  </div>

                  <div className="bg-gradient-to-r from-purple-50 to-purple-100 p-4 rounded-lg border border-purple-200">
                    <div className="flex items-center justify-between">
                      <div>
                        <h3 className="font-semibold text-purple-900 mb-1">智能告警</h3>
                        <p className="text-purple-700 text-sm">异常检测、风险预警</p>
                      </div>
                      <IconAlertTriangle className="w-8 h-8 text-purple-600" />
                    </div>
                    <div className="mt-3">
                      <div className="text-2xl font-bold text-purple-900">5</div>
                      <div className="text-purple-600 text-sm">个告警</div>
                    </div>
                  </div>
                </div>

                {/* AI功能演示区 */}
                <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
                  <Card>
                    <CardHeader>
                      <CardTitle className="flex items-center gap-2">
                        <IconActivity className="w-5 h-5" />
                        实时AI分析
                      </CardTitle>
                      <CardDescription>基于当前数据的AI分析结果</CardDescription>
                    </CardHeader>
                    <CardContent>
                      <div className="space-y-3">
                        <div className="p-3 bg-blue-50 rounded-lg border-l-4 border-blue-500">
                          <p className="font-medium text-blue-900">患者流量预测</p>
                          <p className="text-blue-700 text-sm">预计下午14:00-16:00为高峰期，建议增加2名护士</p>
                        </div>
                        <div className="p-3 bg-yellow-50 rounded-lg border-l-4 border-yellow-500">
                          <p className="font-medium text-yellow-900">设备预警</p>
                          <p className="text-yellow-700 text-sm">CT设备002运行时间过长，建议安排维护检查</p>
                        </div>
                        <div className="p-3 bg-green-50 rounded-lg border-l-4 border-green-500">
                          <p className="font-medium text-green-900">系统状态</p>
                          <p className="text-green-700 text-sm">所有AI模块运行正常，响应时间平均156ms</p>
                        </div>
                      </div>
                    </CardContent>
                  </Card>

                  {/* 新增：Ollama Llava3 多模态AI分析卡片 */}
                  <Card className="border-purple-200 bg-gradient-to-br from-purple-50 to-pink-50">
                    <CardHeader>
                      <CardTitle className="flex items-center gap-2">
                        <div className="relative">
                          <IconActivity className="w-5 h-5 text-purple-600" />
                          <div className="absolute -top-1 -right-1 w-2.5 h-2.5 bg-green-500 rounded-full border border-white"></div>
                        </div>
                        <span className="text-purple-800">Llava3 图像分析</span>
                        <div className="ml-auto">
                          <span className="bg-purple-100 text-purple-700 text-xs font-medium px-2 py-1 rounded-full">
                            13B模型
                          </span>
                        </div>
                      </CardTitle>
                      <CardDescription className="text-purple-600">
                        专业医疗图像AI分析，支持X光、CT、MRI、超声等
                      </CardDescription>
                    </CardHeader>
                    <CardContent>
                      <div className="space-y-3">
                        <div className="p-3 bg-purple-50 rounded-lg border border-purple-200">
                          <div className="flex items-center justify-between mb-2">
                            <p className="font-medium text-purple-900">模型状态</p>
                            <span className="text-xs text-green-600 font-medium">● 在线</span>
                          </div>
                          <p className="text-purple-700 text-sm">Ollama llava:13b 运行正常，平均响应时间 2.3s</p>
                        </div>
                        
                        <div className="p-3 bg-blue-50 rounded-lg border border-blue-200">
                          <div className="flex items-center justify-between mb-2">
                            <p className="font-medium text-blue-900">今日分析</p>
                            <span className="text-sm font-medium text-blue-700">89次</span>
                          </div>
                          <div className="text-xs text-blue-600 space-y-1">
                            <div className="flex justify-between">
                              <span>X光片：</span><span>32次</span>
                            </div>
                            <div className="flex justify-between">
                              <span>CT扫描：</span><span>28次</span>
                            </div>
                            <div className="flex justify-between">
                              <span>其他：</span><span>29次</span>
                            </div>
                          </div>
                        </div>

                        <div className="p-3 bg-green-50 rounded-lg border border-green-200">
                          <p className="font-medium text-green-900">最新分析</p>
                          <p className="text-green-700 text-sm">胸部X光片已完成分析，发现疑似肺部阴影，建议进一步检查</p>
                          <p className="text-xs text-green-600 mt-1">2分钟前 · 置信度：94%</p>
                        </div>
                      </div>

                      {/* Llava3快速操作 */}
                      <div className="mt-4 space-y-2">
                        <Button 
                          onClick={() => {
                            // 打开图像分析模式
                            const event = new CustomEvent('openLlavaAnalysis', { 
                              detail: { mode: 'analysis' } 
                            })
                            window.dispatchEvent(event)
                            toast.success('启动Llava3图像分析...')
                          }}
                          className="w-full bg-purple-600 hover:bg-purple-700 text-white"
                          size="sm"
                        >
                          <IconActivity className="w-4 h-4 mr-2" />
                          启动图像分析
                        </Button>
                        <Button 
                          onClick={() => {
                            const event = new CustomEvent('openLlavaAnalysis', { 
                              detail: { mode: 'chat' } 
                            })
                            window.dispatchEvent(event)
                            toast.success('启动多模态对话...')
                          }}
                          variant="outline"
                          className="w-full border-purple-200 text-purple-700 hover:bg-purple-50"
                          size="sm"
                        >
                          <IconUsers className="w-4 h-4 mr-2" />
                          多模态对话
                        </Button>
                      </div>
                    </CardContent>
                  </Card>

                  <Card>
                    <CardHeader>
                      <CardTitle className="flex items-center gap-2">
                        <IconUsers className="w-5 h-5" />
                        AI使用统计
                      </CardTitle>
                      <CardDescription>今日AI功能使用情况</CardDescription>
                    </CardHeader>
                    <CardContent>
                      <div className="space-y-4">
                        <div className="flex justify-between items-center">
                          <span className="text-sm text-gray-600">智能对话</span>
                          <div className="flex items-center gap-2">
                            <Progress value={75} className="w-20" />
                            <span className="text-sm font-medium">456次</span>
                          </div>
                        </div>
                        <div className="flex justify-between items-center">
                          <span className="text-sm text-gray-600">症状分析</span>
                          <div className="flex items-center gap-2">
                            <Progress value={60} className="w-20" />
                            <span className="text-sm font-medium">234次</span>
                          </div>
                        </div>
                        <div className="flex justify-between items-center">
                          <span className="text-sm text-gray-600">语音识别</span>
                          <div className="flex items-center gap-2">
                            <Progress value={45} className="w-20" />
                            <span className="text-sm font-medium">123次</span>
                          </div>
                        </div>
                        <div className="flex justify-between items-center">
                          <span className="text-sm text-gray-600">图像分析</span>
                          <div className="flex items-center gap-2">
                            <Progress value={30} className="w-20" />
                            <span className="text-sm font-medium">89次</span>
                          </div>
                        </div>
                      </div>
                    </CardContent>
                  </Card>
                </div>

                {/* 快速操作按钮 */}
                <div className="mt-6 flex flex-wrap gap-3">
                  <Button 
                    onClick={() => toast.success('AI助手启动中...')}
                    className="bg-gradient-to-r from-blue-500 to-blue-600"
                  >
                    <IconActivity className="w-4 h-4 mr-2" />
                    启动AI助手
                  </Button>
                  <Button 
                    variant="outline"
                    onClick={() => toast.info('刷新预测数据...')}
                  >
                    <IconTrendingUp className="w-4 h-4 mr-2" />
                    更新预测
                  </Button>
                  <Button 
                    variant="outline"
                    onClick={() => toast.info('导出AI报告...')}
                  >
                    <IconFolder className="w-4 h-4 mr-2" />
                    导出报告
                  </Button>
                </div>
              </div>
            </div>
          </div>
        )

      case 'data-management':
        return (
          <div className="h-full">
            <div className="mb-6">
              <h2 className="text-2xl font-bold text-gray-900 mb-2">数据管理</h2>
              <p className="text-gray-600">医院管理系统数据的导入导出功能</p>
            </div>
            
            <DataManagementPanel />
          </div>
        )

      case 'appointment-management':
        return (
          <div className="h-full">
            <AppointmentManagement />
          </div>
        )

      case 'banner-management':
        return (
          <div className="h-full">
            <BannerManagement />
          </div>
        )

      default:
        return (
          <div className="text-center py-12">
            <IconChartBar className="w-16 h-16 text-gray-400 mx-auto mb-4" />
            <h3 className="text-lg font-medium text-gray-900 mb-2">选择功能模块</h3>
            <p className="text-gray-500">请从左侧菜单选择具体的功能模块</p>
          </div>
        )
    }
  }

  return (
    <div className={`${isFullscreen ? 'h-screen overflow-hidden fullscreen-bg' : 'min-h-screen w-full'} gradient-bg ${isMobile ? 'touch-manipulation' : ''}`}>
      {/* 顶部导航栏 */}
      <div className={`glass-effect border-b border-white/20 dark:border-gray-700/20 ${isFullscreen ? 'fixed top-0 left-0 right-0 z-50 bg-white/90 dark:bg-gray-900/90' : ''}`}>
        <div className={`flex items-center justify-between ${isFullscreen ? 'min-h-12 px-3 py-1' : 'min-h-16 px-4 py-2'} sm:px-6 lg:px-8`}>
          <div className="flex items-center space-x-3 sm:space-x-4 min-w-0 flex-1">
            <div className="text-gray-900 dark:text-gray-100 font-semibold text-sm sm:text-base lg:text-lg whitespace-nowrap flex-shrink-0">{t('app.title', '医疗数字孪生')}</div>
            <Tabs value={selectedTab} onValueChange={handleTabChange} className="flex-1 max-w-4xl">
              <TabsList className={`glass-effect h-8 sm:h-10 lg:h-12 p-0.5 sm:p-1 overflow-x-auto scrollbar-hide flex ${isMobile ? 'scrollbar-none overscroll-x-contain gap-0.5' : 'gap-1'}`}>
                {canAccessTab('dashboard') && (
                  <TabsTrigger
                    value="dashboard"
                    className="glass-button data-[state=active]:bg-white/80 dark:data-[state=active]:bg-gray-800/80 data-[state=active]:text-gray-900 dark:data-[state=active]:text-gray-100 h-7 sm:h-8 lg:h-10 px-2 sm:px-3 lg:px-4 rounded-md sm:rounded-lg whitespace-nowrap text-xs sm:text-sm lg:text-sm flex-shrink-0"
                  >
                    {t('dashboard.tab_dashboard', '仪表板')}
                  </TabsTrigger>
                )}
                {canAccessTab('monitoring') && (
                  <TabsTrigger
                    value="monitoring"
                    className="glass-button data-[state=active]:bg-white/80 dark:data-[state=active]:bg-gray-800/80 data-[state=active]:text-gray-900 dark:data-[state=active]:text-gray-100 h-7 sm:h-8 lg:h-10 px-2 sm:px-3 lg:px-4 rounded-md sm:rounded-lg whitespace-nowrap text-xs sm:text-sm lg:text-sm flex-shrink-0"
                  >
                    {t('dashboard.tab_monitoring', '实时监控')}
                  </TabsTrigger>
                )}
                {canAccessTab('analytics') && (
                  <TabsTrigger
                    value="analytics"
                    className="glass-button data-[state=active]:bg-white/80 dark:data-[state=active]:bg-gray-800/80 data-[state=active]:text-gray-900 dark:data-[state=active]:text-gray-100 h-7 sm:h-8 lg:h-10 px-2 sm:px-3 lg:px-4 rounded-md sm:rounded-lg whitespace-nowrap text-xs sm:text-sm lg:text-sm flex-shrink-0"
                  >
                    {t('dashboard.tab_analytics', '数据分析')}
                  </TabsTrigger>
                )}
                {canAccessTab('optimization') && (
                  <TabsTrigger
                    value="optimization"
                    className="glass-button data-[state=active]:bg-white/80 dark:data-[state=active]:bg-gray-800/80 data-[state=active]:text-gray-900 dark:data-[state=active]:text-gray-100 h-7 sm:h-8 lg:h-10 px-2 sm:px-3 lg:px-4 rounded-md sm:rounded-lg whitespace-nowrap text-xs sm:text-sm lg:text-sm flex-shrink-0"
                  >
                    {t('dashboard.tab_optimization', '优化方案')}
                  </TabsTrigger>
                )}
                {canAccessTab('scenarios') && (
                  <TabsTrigger
                    value="scenarios"
                    className="glass-button data-[state=active]:bg-white/80 dark:data-[state=active]:bg-gray-800/80 data-[state=active]:text-gray-900 dark:data-[state=active]:text-gray-100 h-7 sm:h-8 lg:h-10 px-2 sm:px-3 lg:px-4 rounded-md sm:rounded-lg whitespace-nowrap text-xs sm:text-sm lg:text-sm flex-shrink-0"
                  >
                    {t('dashboard.tab_scenarios', '场景库')}
                  </TabsTrigger>
                )}
                {canAccessTab('management') && (
                  <TabsTrigger
                    value="management"
                    className="glass-button data-[state=active]:bg-white/80 dark:data-[state=active]:bg-gray-800/80 data-[state=active]:text-gray-900 dark:data-[state=active]:text-gray-100 h-7 sm:h-8 lg:h-10 px-2 sm:px-3 lg:px-4 rounded-md sm:rounded-lg whitespace-nowrap text-xs sm:text-sm lg:text-sm flex-shrink-0"
                  >
                    {t('dashboard.tab_management', '管理中心')}
                  </TabsTrigger>
                )}
                {canAccessTab('ocr') && (
                  <TabsTrigger
                    value="ocr"
                    className="glass-button data-[state=active]:bg-white/80 dark:data-[state=active]:bg-gray-800/80 data-[state=active]:text-gray-900 dark:data-[state=active]:text-gray-100 h-7 sm:h-8 lg:h-10 px-2 sm:px-3 lg:px-4 rounded-md sm:rounded-lg whitespace-nowrap text-xs sm:text-sm lg:text-sm flex-shrink-0"
                  >
                    OCR识别
                  </TabsTrigger>
                )}
              </TabsList>
            </Tabs>
          </div>

          {/* 用户角色和语言切换 */}
          <div className="flex items-center space-x-1 sm:space-x-2 lg:space-x-3 flex-shrink-0">
            {/* 当前用户信息 - 在小屏幕上隐藏 */}
            {isMounted && currentUser && (
              <div className="hidden xl:flex items-center space-x-3">
                <div className="text-right">
                  <div className="text-sm font-medium text-gray-900 dark:text-gray-100">
                    {currentUser.username}
                  </div>
                  <div className="text-xs text-gray-500 dark:text-gray-400">
                    {currentUser.email || '暂无邮箱'}
                  </div>
                </div>
                <div className="w-8 h-8 bg-gradient-to-r from-blue-500 to-blue-600 rounded-full flex items-center justify-center text-white text-sm font-medium">
                  {currentUser.username?.charAt(0)?.toUpperCase() || 'U'}
                </div>
              </div>
            )}

            {/* 用户角色显示 */}
            {isMounted && (
              <div className="flex items-center space-x-1 sm:space-x-2 px-1 sm:px-2 lg:px-3 py-1 bg-cyan-50 dark:bg-cyan-900/20 rounded-lg border border-cyan-200 dark:border-cyan-700">
                <div className="w-2 h-2 bg-cyan-500 rounded-full"></div>
                <span className="text-xs sm:text-sm font-medium text-cyan-700 dark:text-cyan-300 whitespace-nowrap">
                  {getRoleDisplayName(currentUserRole)}
                </span>
              </div>
            )}

            {/* 语言切换按钮 */}
            <LanguageSwitcher />



            {/* 用户下拉菜单 */}
            {isMounted && (
              <UserDropdown
                username={currentUser?.username || '用户'}
                onLogout={handleLogout}
              />
            )}
          </div>
        </div>
      </div>

      {/* 检查是否需要显示侧边栏 */}
      {selectedTab === 'monitoring' || selectedTab === 'analytics' ? (
        <div className={`flex flex-col lg:flex-row ${isFullscreen ? 'pt-12' : ''}`}>
          {/* 左侧导航菜单 - 响应式侧边栏 */}
          <div className={`${
            shouldShowSidebar() 
              ? `w-full ${screenSize === 'lg' ? 'lg:w-56' : 'lg:w-64'} glass-effect border-b lg:border-b-0 lg:border-r border-white/20 dark:border-gray-700/20 min-h-0 lg:min-h-screen`
              : 'hidden'
          } ${screenSize === 'sm' || screenSize === 'md' ? 'order-2 lg:order-1' : ''}`}>
            <div className="p-4">
              {/* 树形菜单 */}
              <div className="space-y-2">
                {selectedTab === 'monitoring' && (
                  <>
                    <div
                      className={`group flex items-center space-x-3 px-4 py-3 rounded-xl cursor-pointer transition-all duration-200 ${selectedMenu === 'realtime'
                        ? 'bg-gradient-to-r from-blue-500 to-blue-600 text-white shadow-lg shadow-blue-500/25'
                        : 'text-slate-600 hover:bg-slate-100 hover:text-slate-800'
                        }`}
                      onClick={() => handleMenuClick('realtime')}
                    >
                      <div className={`w-8 h-8 rounded-lg flex items-center justify-center ${selectedMenu === 'realtime' ? 'bg-white/20' : 'bg-slate-100'
                        }`}>
                        <IconEye className={`w-4 h-4 ${selectedMenu === 'realtime' ? 'text-white' : 'text-slate-500'}`} />
                      </div>
                      <span className="font-medium">实时数据</span>
                    </div>

                    <div
                      className={`group flex items-center space-x-3 px-4 py-3 rounded-xl cursor-pointer transition-all duration-200 ${selectedMenu === 'system'
                        ? 'bg-gradient-to-r from-blue-500 to-blue-600 text-white shadow-lg shadow-blue-500/25'
                        : 'text-slate-600 hover:bg-slate-100 hover:text-slate-800'
                        }`}
                      onClick={() => handleMenuClick('system')}
                    >
                      <div className={`w-8 h-8 rounded-lg flex items-center justify-center ${selectedMenu === 'system' ? 'bg-white/20' : 'bg-slate-100'
                        }`}>
                        <IconActivity className={`w-4 h-4 ${selectedMenu === 'system' ? 'text-white' : 'text-slate-500'}`} />
                      </div>
                      <span className="font-medium">系统状态</span>
                    </div>

                    <div
                      className={`group flex items-center space-x-3 px-4 py-3 rounded-xl cursor-pointer transition-all duration-200 ${selectedMenu === 'devices'
                        ? 'bg-gradient-to-r from-blue-500 to-blue-600 text-white shadow-lg shadow-blue-500/25'
                        : 'text-slate-600 hover:bg-slate-100 hover:text-slate-800'
                        }`}
                      onClick={() => handleMenuClick('devices')}
                    >
                      <div className={`w-8 h-8 rounded-lg flex items-center justify-center ${selectedMenu === 'devices' ? 'bg-white/20' : 'bg-slate-100'
                        }`}>
                        <IconBed className={`w-4 h-4 ${selectedMenu === 'devices' ? 'text-white' : 'text-slate-500'}`} />
                      </div>
                      <span className="font-medium">设备监控</span>
                    </div>
                  </>
                )}

                {selectedTab === 'analytics' && (
                  <>
                    <div
                      className={`group flex items-center space-x-3 px-4 py-3 rounded-xl cursor-pointer transition-all duration-200 ${selectedMenu === 'history'
                        ? 'bg-gradient-to-r from-emerald-500 to-emerald-600 text-white shadow-lg shadow-emerald-500/25'
                        : 'text-slate-600 hover:bg-slate-100 hover:text-slate-800'
                        }`}
                      onClick={() => handleMenuClick('history')}
                    >
                      <div className={`w-8 h-8 rounded-lg flex items-center justify-center ${selectedMenu === 'history' ? 'bg-white/20' : 'bg-slate-100'
                        }`}>
                        <IconTrendingUp className={`w-4 h-4 ${selectedMenu === 'history' ? 'text-white' : 'text-slate-500'}`} />
                      </div>
                      <span className="font-medium">历史趋势</span>
                    </div>

                    <div
                      className={`group flex items-center space-x-3 px-4 py-3 rounded-xl cursor-pointer transition-all duration-200 ${selectedMenu === 'patients'
                        ? 'bg-gradient-to-r from-emerald-500 to-emerald-600 text-white shadow-lg shadow-emerald-500/25'
                        : 'text-slate-600 hover:bg-slate-100 hover:text-slate-800'
                        }`}
                      onClick={() => handleMenuClick('patients')}
                    >
                      <div className={`w-8 h-8 rounded-lg flex items-center justify-center ${selectedMenu === 'patients' ? 'bg-white/20' : 'bg-slate-100'
                        }`}>
                        <IconUsers className={`w-4 h-4 ${selectedMenu === 'patients' ? 'text-white' : 'text-slate-500'}`} />
                      </div>
                      <span className="font-medium">患者管理</span>
                    </div>

                    <div
                      className={`group flex items-center space-x-3 px-4 py-3 rounded-xl cursor-pointer transition-all duration-200 ${selectedMenu === 'departments'
                        ? 'bg-gradient-to-r from-emerald-500 to-emerald-600 text-white shadow-lg shadow-emerald-500/25'
                        : 'text-slate-600 hover:bg-slate-100 hover:text-slate-800'
                        }`}
                      onClick={() => handleMenuClick('departments')}
                    >
                      <div className={`w-8 h-8 rounded-lg flex items-center justify-center ${selectedMenu === 'departments' ? 'bg-white/20' : 'bg-slate-100'
                        }`}>
                        <IconFolder className={`w-4 h-4 ${selectedMenu === 'departments' ? 'text-white' : 'text-slate-500'}`} />
                      </div>
                      <span className="font-medium">科室管理</span>
                    </div>

                    <div
                      className={`group flex items-center space-x-3 px-4 py-3 rounded-xl cursor-pointer transition-all duration-200 ${selectedMenu === 'hospital-map'
                        ? 'bg-gradient-to-r from-emerald-500 to-emerald-600 text-white shadow-lg shadow-emerald-500/25'
                        : 'text-slate-600 hover:bg-slate-100 hover:text-slate-800'
                        }`}
                      onClick={() => handleMenuClick('hospital-map')}
                    >
                      <div className={`w-8 h-8 rounded-lg flex items-center justify-center ${selectedMenu === 'hospital-map' ? 'bg-white/20' : 'bg-slate-100'
                        }`}>
                        <IconMap className={`w-4 h-4 ${selectedMenu === 'hospital-map' ? 'text-white' : 'text-slate-500'}`} />
                      </div>
                      <span className="font-medium">地图管理</span>
                    </div>

                    {/* AI智能控制台 */}
                    <div
                      className={`group flex items-center space-x-3 px-4 py-3 rounded-xl cursor-pointer transition-all duration-200 ${selectedMenu === 'ai-control'
                        ? 'bg-gradient-to-r from-purple-500 to-pink-600 text-white shadow-lg shadow-purple-500/25'
                        : 'text-slate-600 hover:bg-slate-100 hover:text-slate-800'
                        }`}
                      onClick={() => handleMenuClick('ai-control')}
                    >
                      <div className={`w-8 h-8 rounded-lg flex items-center justify-center ${selectedMenu === 'ai-control' ? 'bg-white/20' : 'bg-slate-100'
                        }`}>
                        <IconChartBar className={`w-4 h-4 ${selectedMenu === 'ai-control' ? 'text-white' : 'text-slate-500'}`} />
                      </div>
                      <span className="font-medium">AI智能中心</span>
                    </div>

                    {/* 数据管理 */}
                    <div
                      className={`group flex items-center space-x-3 px-4 py-3 rounded-xl cursor-pointer transition-all duration-200 ${selectedMenu === 'data-management'
                        ? 'bg-gradient-to-r from-blue-500 to-indigo-600 text-white shadow-lg shadow-blue-500/25'
                        : 'text-slate-600 hover:bg-slate-100 hover:text-slate-800'
                        }`}
                      onClick={() => handleMenuClick('data-management')}
                    >
                      <div className={`w-8 h-8 rounded-lg flex items-center justify-center ${selectedMenu === 'data-management' ? 'bg-white/20' : 'bg-slate-100'
                        }`}>
                        <IconDatabase className={`w-4 h-4 ${selectedMenu === 'data-management' ? 'text-white' : 'text-slate-500'}`} />
                      </div>
                      <span className="font-medium">数据管理</span>
                    </div>

                    {/* 预约管理 */}
                    <div
                      className={`group flex items-center space-x-3 px-4 py-3 rounded-xl cursor-pointer transition-all duration-200 ${selectedMenu === 'appointment-management'
                        ? 'bg-gradient-to-r from-orange-500 to-red-600 text-white shadow-lg shadow-orange-500/25'
                        : 'text-slate-600 hover:bg-slate-100 hover:text-slate-800'
                        }`}
                      onClick={() => handleMenuClick('appointment-management')}
                    >
                      <div className={`w-8 h-8 rounded-lg flex items-center justify-center ${selectedMenu === 'appointment-management' ? 'bg-white/20' : 'bg-slate-100'
                        }`}>
                        <IconCalendar className={`w-4 h-4 ${selectedMenu === 'appointment-management' ? 'text-white' : 'text-slate-500'}`} />
                      </div>
                      <span className="font-medium">预约管理</span>
                    </div>

                    {/* 轮播图管理 */}
                    <div
                      className={`group flex items-center space-x-3 px-4 py-3 rounded-xl cursor-pointer transition-all duration-200 ${selectedMenu === 'banner-management'
                        ? 'bg-gradient-to-r from-pink-500 to-rose-600 text-white shadow-lg shadow-pink-500/25'
                        : 'text-slate-600 hover:bg-slate-100 hover:text-slate-800'
                        }`}
                      onClick={() => handleMenuClick('banner-management')}
                    >
                      <div className={`w-8 h-8 rounded-lg flex items-center justify-center ${selectedMenu === 'banner-management' ? 'bg-white/20' : 'bg-slate-100'
                        }`}>
                        <IconPhoto className={`w-4 h-4 ${selectedMenu === 'banner-management' ? 'text-white' : 'text-slate-500'}`} />
                      </div>
                      <span className="font-medium">轮播图管理</span>
                    </div>
                  </>
                )}
              </div>

              {/* 底部装饰 */}
              <div className="mt-8 pt-6 border-t border-slate-200/60">
                <div className="text-xs text-slate-400 text-center">
                  {selectedTab === 'monitoring' ? '实时监控模块' : '数据分析模块'}
                </div>
              </div>
            </div>
          </div>

          {/* 主内容区域 - 有侧边栏时 */}
          <div className={`flex-1 ${screenSize === 'sm' || screenSize === 'md' ? 'order-1 lg:order-2' : ''}`}>
            <Tabs value={selectedTab} onValueChange={handleTabChange} className="w-full">
              <TabsContent value="monitoring" className={`${screenSize === 'sm' ? 'p-3' : screenSize === 'md' ? 'p-4' : 'p-6'}`}>
                {renderMenuContent()}
              </TabsContent>

              <TabsContent value="analytics" className={`${screenSize === 'sm' ? 'p-3' : screenSize === 'md' ? 'p-4' : 'p-6'}`}>
                {renderMenuContent()}
              </TabsContent>
            </Tabs>
          </div>
        </div>
      ) : (
        /* 没有侧边栏的Tab - 全宽布局 */
        <div className={`w-full ${isFullscreen ? 'pt-12' : ''}`}>
          <Tabs value={selectedTab} onValueChange={handleTabChange} className="w-full">
            <TabsContent value="dashboard" className={`${screenSize === 'sm' ? 'p-2' : 'p-0'}`}>
              <VisualizationDashboard 
                screenSize={screenSize}
                windowSize={windowSize}
                isFullscreen={isFullscreen}
                isMobile={isMobile}
                isTablet={isTablet}
                scaleFactor={scaleFactor}
                baseFontSize={baseFontSize}
              />
            </TabsContent>

            <TabsContent value="optimization" className="p-6">
              {canAccessTab('optimization') ? (
                <div className="text-center py-12">
                  <IconTarget className="w-16 h-16 text-gray-400 mx-auto mb-4" />
                  <h3 className="text-lg font-medium text-gray-900 mb-2">{t('dashboard.tab_optimization', '优化方案')}</h3>
                  <p className="text-gray-500 mb-4">多目标优化与约束校验，方案推荐与报告生成</p>
                  <Button onClick={() => window.open('/optimization', '_blank')}>
                    查看详细优化方案
                  </Button>
                </div>
              ) : (
                <div className="text-center py-12">
                  <div className="w-16 h-16 bg-red-100 rounded-full flex items-center justify-center mx-auto mb-4">
                    <span className="text-red-500 text-2xl">🔒</span>
                  </div>
                  <h3 className="text-lg font-medium text-gray-900 mb-2">
                    {locale === 'zh-CN' ? '权限不足' : 'Access Denied'}
                  </h3>
                  <p className="text-gray-500">
                    {locale === 'zh-CN'
                      ? `当前角色 "${getRoleDisplayName(currentUserRole)}" 无权访问此功能`
                      : `Current role "${getRoleDisplayName(currentUserRole)}" does not have access to this feature`
                    }
                  </p>
                </div>
              )}
            </TabsContent>

            <TabsContent value="scenarios" className="p-6">
              {canAccessTab('scenarios') ? (
                <div className="text-center py-12">
                  <IconFolder className="w-16 h-16 text-gray-400 mx-auto mb-4" />
                  <h3 className="text-lg font-medium text-gray-900 mb-2">{t('dashboard.tab_scenarios', '场景库管理')}</h3>
                  <p className="text-gray-500 mb-4">仿真场景的创建、管理和版本控制</p>
                  <Button onClick={() => window.open('/scenarios', '_blank')}>
                    管理场景库
                  </Button>
                </div>
              ) : (
                <div className="text-center py-12">
                  <div className="w-16 h-16 bg-red-100 rounded-full flex items-center justify-center mx-auto mb-4">
                    <span className="text-red-500 text-2xl">🔒</span>
                  </div>
                  <h3 className="text-lg font-medium text-gray-900 mb-2">
                    {locale === 'zh-CN' ? '权限不足' : 'Access Denied'}
                  </h3>
                  <p className="text-gray-500">
                    {locale === 'zh-CN'
                      ? `当前角色 "${getRoleDisplayName(currentUserRole)}" 无权访问此功能`
                      : `Current role "${getRoleDisplayName(currentUserRole)}" does not have access to this feature`
                    }
                  </p>
                </div>
              )}
            </TabsContent>

            <TabsContent value="management" className="p-6">
              {/* 管理中心内容 */}
              {renderRoleBasedDashboard()}
            </TabsContent>


            <TabsContent value="hospital-map" className="p-0 h-full">
              {renderMenuContent()}
            </TabsContent>

            <TabsContent value="ocr" className="p-0 h-full">
              <OcrDashboard />
            </TabsContent>
          </Tabs>
        </div>
      )}

      {/* 添加POI对话框 */}
      {showAddPOI && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <Card className="w-96 max-w-full mx-4">
            <CardHeader>
              <CardTitle>添加POI点位</CardTitle>
              <CardDescription>在选中位置添加医院设施或科室</CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              <div>
                <Label htmlFor="poi-name">名称</Label>
                <Input
                  id="poi-name"
                  value={poiForm.name}
                  onChange={(e) => setPOIForm(prev => ({ ...prev, name: e.target.value }))}
                  placeholder="输入POI名称"
                />
              </div>

              <div>
                <Label htmlFor="poi-type">类型</Label>
                <Select
                  value={poiForm.type}
                  onValueChange={(value) => setPOIForm(prev => ({ ...prev, type: value as POIData['type'] }))}
                >
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    {Object.entries(config.hospital.poiTypes).map(([value, label]) => (
                      <SelectItem key={value} value={value}>
                        {label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>

              <div>
                <Label htmlFor="poi-floor">楼层</Label>
                <Select
                  value={poiForm.floor}
                  onValueChange={(value) => setPOIForm(prev => ({ ...prev, floor: value }))}
                >
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    {config.hospital.defaultFloors.map((floor) => (
                      <SelectItem key={floor} value={floor}>
                        {floor}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>

              <div>
                <Label htmlFor="poi-description">描述</Label>
                <Input
                  id="poi-description"
                  value={poiForm.description}
                  onChange={(e) => setPOIForm(prev => ({ ...prev, description: e.target.value }))}
                  placeholder="输入描述信息（可选）"
                />
              </div>

              <div className="flex justify-end space-x-2">
                <Button
                  variant="outline"
                  onClick={() => setShowAddPOI(false)}
                >
                  取消
                </Button>
                <Button onClick={async () => {
                  if (!selectedPosition && !selectedModel) {
                    toast.error('请先在地图上选择位置')
                    return
                  }

                  try {
                    const position: [number, number] = selectedPosition || [0, 0]
                    
                    const newPOI: POIData = {
                      id: `poi_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
                      name: poiForm.name,
                      type: poiForm.type,
                      position,
                      floor: poiForm.floor,
                      description: poiForm.description
                    }

                    // 注册到POI目录，这样其他页面可以引用
                    poiCatalog.registerPOI(newPOI)
                    
                    // 也保存到数据库
                    try {
                      await hospitalDB.addPOI({
                        hospitalId: 'default_hospital',
                        floorId: poiForm.floor,
                        name: poiForm.name,
                        type: poiForm.type,
                        position,
                        description: poiForm.description,
                        status: 'active',
                        metadata: {
                          addedFrom: selectedModel ? 'model' : 'map',
                          modelObject: selectedModel?.object?.name
                        }
                      })
                    } catch (dbError) {
                      console.warn('数据库保存失败:', dbError)
                    }

                    setPOIs(prev => [...prev, newPOI])
                    
                    // 直接添加到地图
                    if (mapViewerRef.current) {
                      mapViewerRef.current.addPOI(newPOI)
                    }
                    
                    // if (viewerRef.current) {
                    //   viewerRef.current.addPOI(newPOI)
                    // }

                    setPOIForm({
                      name: '',
                      type: 'department',
                      floor: 'L1',
                      description: ''
                    })
                    setShowAddPOI(false)
                    setSelectedPosition(null)
                    setSelectedModel(null)
                    
                    toast.success('POI添加成功', {
                      description: `POI ID: ${newPOI.id}`,
                      action: {
                        label: '复制分享链接',
                        onClick: () => {
                          const shareUrl = `${window.location.origin}/dashboard?poiIds=${newPOI.id}&zoom=18`
                          navigator.clipboard.writeText(shareUrl)
                          toast.success('分享链接已复制到剪贴板')
                        }
                      }
                    })
                  } catch (error) {
                    console.error('添加POI失败:', error)
                    toast.error('添加POI失败')
                  }
                }}>
                  添加
                </Button>
              </div>
            </CardContent>
          </Card>
        </div>
      )}

      {/* 添加商铺对话框 */}
      {showAddStore && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <Card className="w-96 max-w-full mx-4">
            <CardHeader>
              <CardTitle>添加商铺</CardTitle>
              <CardDescription>在选中位置添加商业设施</CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              <div>
                <Label htmlFor="store-name">商铺名称</Label>
                <Input
                  id="store-name"
                  value={storeForm.name}
                  onChange={(e) => setStoreForm(prev => ({ ...prev, name: e.target.value }))}
                  placeholder="输入商铺名称"
                />
              </div>

              <div>
                <Label htmlFor="store-business">业态</Label>
                <Input
                  id="store-business"
                  value={storeForm.business}
                  onChange={(e) => setStoreForm(prev => ({ ...prev, business: e.target.value }))}
                  placeholder="例如：餐饮、零售、服务"
                />
              </div>

              <div>
                <Label htmlFor="store-description">描述</Label>
                <Input
                  id="store-description"
                  value={storeForm.description}
                  onChange={(e) => setStoreForm(prev => ({ ...prev, description: e.target.value }))}
                  placeholder="输入描述信息（可选）"
                />
              </div>

              <div className="flex justify-end space-x-2">
                <Button
                  variant="outline"
                  onClick={() => setShowAddStore(false)}
                >
                  取消
                </Button>
                <Button onClick={async () => {
                  if (!selectedPosition && !selectedModel) {
                    toast.error('请先在地图上选择位置')
                    return
                  }

                  try {
                    const position: [number, number] = selectedPosition || [0, 0]
                    
                    const newStore: StoreData = {
                      id: `store_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
                      name: storeForm.name,
                      business: storeForm.business,
                      lnglat: position,
                      metadata: {
                        addedFrom: selectedModel ? 'model' : 'map',
                        modelObject: selectedModel?.object?.name,
                        description: storeForm.description
                      }
                    }

                    setStores(prev => [...prev, newStore])
                    
                    // if (viewerRef.current) {
                    //   viewerRef.current.addStore(newStore)
                    // }

                    setStoreForm({
                      name: '',
                      business: '',
                      description: ''
                    })
                    setShowAddStore(false)
                    setSelectedPosition(null)
                    setSelectedModel(null)
                    
                    toast.success('商铺添加成功')
                  } catch (error) {
                    console.error('添加商铺失败:', error)
                    toast.error('添加商铺失败')
                  }
                }}>
                  添加
                </Button>
              </div>
            </CardContent>
          </Card>
        </div>
      )}

      {/* AI智能助手 - 只在地图管理时显示 */}
      {selectedMenu === 'hospital-map' && (
        <AIAssistant
          hospitalId="default_hospital"
          onNavigateTo={(location) => {
            // if (viewerRef.current) {
            //   viewerRef.current.flyTo([location.lng, location.lat], 18)
            // }
            toast.success(`正在导航到 ${location.name}`)
          }}
          onBookAppointment={(department, doctor) => {
            toast.success(`正在为您预约 ${department}${doctor ? ` - ${doctor}` : ''}`)
          }}
          onGetInfo={(type, name) => {
            toast.success(`正在查询 ${name} 的相关信息`)
          }}
        />
      )}

      {/* 底部版权信息 */}
      <div className={`bg-white border-t text-center py-4 text-sm text-gray-500 transition-all duration-300 ${isFullscreen ? 'hidden' : 'block'}`}>
        医疗数字孪生系统 ©2025 Created by 医疗团队
      </div>

      {/* Ollama Llava3 AI助手 - 监听dashboard的启动事件 */}
      <OllamaLlavaAssistant 
        userId="dashboard-user"
        initialMode="analysis"
        onAnalysisComplete={(result) => {
          console.log('Dashboard - 图像分析完成:', result)
          toast.success('图像分析完成！', {
            description: `模型: ${result.metadata?.model} | 耗时: ${result.metadata?.processingTime}ms`
          })
        }}
      />
    </div>
  )
}
